Chisel variable Declaration Syntax Meaning rvs: Bool* - chisel

Looking at object DecoupledHelper and class DecoupledHelper code, I see the following.
object DecoupledHelper {
def apply(rvs: Bool*) = new DecoupledHelper(rvs)
}
class DecoupledHelper(val rvs: Seq[Bool]) {
def fire(exclude: Bool, includes: Bool*) = {
(rvs.filter(_ ne exclude) ++ includes).reduce(_ && _)
}
}
I don't understand the parameters declaration syntax in apply method. (rvs: Bool*). What is the meaning of * at end of Type Bool.
Looking at constructor parameters of class DecoupledHelper, it expects (rvs: Seq[Bool])
Does this mean that type Bool* is automatically converted to type Seq[Bool]?
While at this, can anyone also explain what rvs.filter method is doing?

As Kamyar said, Type* is the Scala syntax for variable number of arguments (also known as "varags"). It let's you call the DecoupledHelper apply method like so:
val helper = DecoupledHelper(a, b, c) // calling apply on the companion object
// instead of
val helper2 = new DecoupledHelper(Seq(a, b, c)) // calling constructor of the class
For those new to Chisel and Scala, note that apply is a special function Scala that is called when you "apply" parentheses to an object or instance. Thus DecoupledHelper(a, b, c) is equivalent to DecoupledHelper.apply(a, b, c).
While at this, can anyone also explain what rvs.filter method is doing?
It is taking advantage of the implementation of Chisel which I would not recommend doing. ne is the Scala function for not referentially equal. It lets you check if two object are not the same object in memory.
In this case, it let's you do things like the following:
val helper = DecoupledHelper(a, b, c)
helper.fire() // a && b && c
helper.fire(b) // a && c
Now because this is dangerously using referential equality instead of actual hardware equality (and there are limitations of the implementation that motivated this), something that should work does not:
val helper = DecoupledHelper(a, b, c)
val d = b // Same reference
val e = WireInit(b) // Equivalent Wire but different reference
helper.fire(d) // a && c
helper.fire(e) // a && b && c
d points to the same object on the heap as b, but e does not despite the fact that it is equivalent from the hardware perspective.
For more information, see the related bug report and discussion: https://github.com/chipsalliance/rocket-chip/issues/1616

Related

Representing Functions as Types

A function can be a highly nested structure:
function a(x) {
return b(c(x), d(e(f(x), g())))
}
First, wondering if a function has an instance. That is, the evaluation of the function being the instance of the function. In that sense, the type is the function, and the instance is the evaluation of it. If it can be, then how to model a function as a type (in some type-theory oriented language like Haskell or Coq).
It's almost like:
type a {
field: x
constructor b {
constructor c {
parameter: x
},
...
}
}
But I'm not sure if I'm not on the right track. I know you can say a function has a [return] type. But I'm wondering if a function can be considered a type, and if so, how to model it as a type in a type-theory-oriented language, where it models the actual implementation of the function.
I think the problem is that types based directly on the implementation (let's call them "i-types") don't seem very useful, and we already have good ways of modelling them (called "programs" -- ha ha).
In your specific example, the full i-type of your function, namely:
type a {
field: x
constructor b {
constructor c {
parameter: x
},
constructor d {
constructor e {
constructor f {
parameter: x
}
constructor g {
}
}
}
}
is just a verbose, alternative syntax for the implementation itself. That is, we could write this i-type (in a Haskell-like syntax) as:
itype a :: a x = b (c x) (d (e (f x) g))
On the other hand, we could convert your function implementation to Haskell term-level syntax directly to write it as:
a x = b (c x) (d (e (f x) g))
and the i-type and the implementation are exactly the same thing.
How would you use these i-types? The compiler might use them by deriving argument and return types to type-check the program. (Fortunately, there are well known algorithms, such as Algorithm W, for simultaneously deriving and type-checking argument and return types from i-types of this sort.) Programmers probably wouldn't use i-types directly -- they're too complicated to use for refactoring or reasoning about program behavior. They'd probably want to look at the types derived by the compiler for the arguments and return type.
In particular, "modelling" these i-types at the type level in Haskell doesn't seem productive. Haskell can already model them at the term level. Just write your i-types as a Haskell program:
a x = b (c x) (d (e (f x) g))
b s t = sqrt $ fromIntegral $ length (s ++ t)
c = show
d = reverse
e c ds = show (sum ds + fromIntegral (ord c))
f n = if even n then 'E' else 'O'
g = [1.5..5.5]
and don't run it. Congratulations, you've successfully modelled these i-types! You can even use GHCi to query derived argument and return types:
> :t a
a :: Floating a => Integer -> a -- "a" takes an Integer and returns a float
>
Now, you are perhaps imagining that there are situations where the implementation and i-type would diverge, maybe when you start introducing literal values. For example, maybe you feel like the function f above:
f n = if even n then 'E' else 'O'
should be assigned a type something like the following, that doesn't depend on the specific literal values:
type f {
field: n
if_then_else {
constructor even { -- predicate
parameter: n
}
literal Char -- then-branch
literal Char -- else-branch
}
Again, though, you'd be better off defining an arbitrary term-level Char, like:
someChar :: Char
someChar = undefined
and modeling this i-type at the term-level:
f n = if even n then someChar else someChar
Again, as long as you don't run the program, you've successfully modelled the i-type of f, can query its argument and return types, type-check it as part of a bigger program, etc.
I'm not clear exactly what you are aiming at, so I'll try to point at some related terms that you might want to read about.
A function has not only a return type, but a type that describes its arguments as well. So the (Haskell) type of f reads "f takes an Int and a Float, and returns a List of Floats."
f :: Int -> Float -> [Float]
f i x = replicate i x
Types can also describe much more of the specification of a function. Here, we might want the type to spell out that the length of the list will be the same as the first argument, or that every element of the list will be the same as the second argument. Length-indexed lists (often called Vectors) are a common first example of Dependent Types.
You might also be interested in functions that take types as arguments, and return types. These are sometimes called "type-level functions". In Coq or Idris, they can be defined the same way as more familiar functions. In Haskell, we usually implement them using Type Families, or using Type Classes with Functional Dependencies.
Returning to the first part of your question, Beta Reduction is the process of filling in concrete values for each of the function's arguments. I've heard people describe expressions as "after reduction" or "fully reduced" to emphasize some stage in this process. This is similar to a function Call Site, but emphasizes the expression & arguments, rather than the surrounding context.

Scala: Passing Vs applying function

Let's say we have the following code snippet:
List(1, 2, 3)
.map(doubleIt) // passing function
.map(x => doubleIt(x)) // applying function
def doubleIt(i: Int): Int = 2 * i
As you can see we can either pass doubleIt as a function literal or apply it inside another anonymous Lambda. I have always wondered which approach is better. I personally prefer passing a function literal as it seems like second approach would end up creating an extra wrapper Lambda for no good reason, but I am not 100% positive my reasoning is correct.
I am curious to know what the pro/cons of each style are and whether one is definitely better than the other.
This might change in Scala 2.12+, but at the moment both approaches are identical. As a test, I created the following:
class Test {
def testPassingFunction: List[Int] = List(1, 2, 3).map(doubleIt)
def testApplyingFunction: List[Int] = List(1, 2, 3).map(x => doubleIt(x))
def doubleIt(i: Int): Int = 2 * i
}
I then compiled it and used javap to disassemble the bytecode. Both functions are identical (except for different Strings. In all cases a new class that extends from Function1 is created that calls the appropriate method. As #Mike says in the comments, the Scala compiler converts everything to the second form.
It turns out that it depends somewhat on what your "function" is. If it is actually a function (that is, a function value, defined as val doubleIt = (x: Int) => 2 * x), then your hunch is correct. The version in which you pass a function literal that simply applies doubleIt (i.e., l map { x => doubleIt(x) } is compiled just as written, resulting in an anonymous function that delegates to doubleIt. Passing doubleIt as a function value takes out the middle man. If doubleIt is a method, on the other hand, then both forms are compiled identically.
You can easily verify this yourself at the REPL. Define the following class:
class A {
val l = List(1,2,3)
val f = (x: Int) => 2 * x
def g(x: Int) = 2 * x
def m1 = l map f
def m2 = l map { x => f(x) }
def m3 = l map g
def m4 = l map { x => g(x) }
}
Then run :power and :javap -v A.
That said, the distinction is unlikely to make a practical difference in any but the most performance-critical code. In ordinary circumstances, code clarity is the more important consideration and depends somewhat on who will be reading your code in the future. Personally, I tend to prefer the concise lst map doubleIt form; this form eliminates a bunch of syntactic noise that adds nothing semantically. I suppose the longer form may be considered more explicit, especially for developers that aren't very familiar with the map method. The literal reading matches the intent quite well: "(Given) list, map (each) x to doubleIt(x)". Your team will have to decide what's best for you and your organization.

controlling program flow without if-else / switch-case statements

Let's say I have 1000 functions defined as follows
void func dummy1(int a);
void func dummy2(int a, int aa);
void func dummy3(int a, int aa, int aaa);
.
.
.
void func dummy1000(int a, int aa, int aaa, ...);
I want to write a function that takes an integer, n (n < 1000) and calls nth dummy function (in case of 10, dummy10) with exactly n arguments(arguments can be any integer, let's say 0) as required. I know this can be achieved by writing a switch case statement with 1000 cases which is not plausible.
In my opinion, this cannot be achieved without recompilation at run time so languages like java, c, c++ will never let such a thing happen.
Hopefully, there is a way to do this. If so I am curious.
Note: This is not something that I will ever use, I asked question just because of my curiosity.
In modern functional languages, you can make a list of functions which take a list as an argument. This will arguably solve your problem, but it is also arguably cheating, as it is not quite the statically-typed implementation your question seems to imply. However, it is pretty much what dynamic languages such as Python, Ruby, or Perl do when using "manual" argument handling...
Anyway, the following is in Haskell: it supplies the nth function (from its first argument fs) a list of n copies of the second argument (x), and returns the result. Of course, you will need to put together the list of functions somehow, but unlike a switch statement this list will be reusable as a first-class argument.
selectApplyFunction :: [ [Int] -> a ] -> Int -> Int -> a
selectApplyFunction fs x n = (fs !! (n-1)) (replicate n x)
dummy1 [a] = 5 * a
dummy2 [a, b] = (a + 3) * b
dummy3 [a, b, c] = (a*b*c) / (a*b + b*c + c*a)
...
myFunctionList = [ dummy1, dummy2, dummy3, ... ]
-- (myfunction n) provides n copies of the number 42 to the n'th function
myFunction = selectApplyFunction myFunctionList 42
-- call the 666'th function with 666 copies of 42
result = myFunction 666
Of course, you will get an exception if n is greater than the number of functions, or if the function can't handle the list it is given. Note, too, that it is poor Haskell style -- mainly because of the way it abuses lists to (abusively) solve your problem...
No, you are incorrect. Most modern languages support some form of Reflection that will allow you to call a function by name and pass params to it.
You can create an array of functions in most of modern languages.
In pseudo code,
var dummy = new Array();
dummy[1] = function(int a);
dummy[2] = function(int a, int aa);
...
var result = dummy[whateveryoucall](1,2,3,...,whateveryoucall);
In functional languages you could do something like this, in strongly typed ones, like Haskell, the functions must have the same type, though:
funs = [reverse, tail, init] -- 3 functions of type [a]->[a]
run fn arg = (funs !! fn) $ args -- applies function at index fn to args
In object oriented languages, you can use function objects and reflection together to achieve exactly what you want. The problem of the variable number of arguments is solved by passing appropriate POJOs (recalling C stucts) to the function object.
interface Functor<A,B> {
public B compute(A input);
}
class SumInput {
private int x, y;
// getters and setters
}
class Sum implements Functor<SumInput, Integer> {
#Override
public Integer compute(SumInput input) {
return input.getX() + input.getY();
}
}
Now imagine you have a large number of these "functors". You gather them in a configuration file (maybe an XML file with metadata about each functor, usage scenarios, instructions, etc...) and return the list to the user.
The user picks one of them. By using reflection, you can see what is the required input and the expected output. The user fills in the input, and by using reflection you instantiate the functor class (newInstance()), call the compute() function and get the output.
When you add a new functor, you just have to change the list of the functors in the config file.

Passing expression as a parameter in Call by reference

All,
When we are passing an expression as a parameter, how does the evaluation occur? Here is a small example. This is just a pseudocode kind of example:
f (x,y)
{
y = y+1;
x = x+y;
}
main()
{
a = 2; b = 2;
f(a+b, a)
print a;
}
When accessing variable x in f, does it access the address of the temp variable which contains the result of a+b or will it access the individual addresses of a and b and then evaluate the value of a+b
Please help.
Regards,
darkie15
Somewhat language dependent, but in C++
f(a+b, a)
evaluates a + b and and pushes the result of evaluation onto the stack and then passes references to this value to f(). This will only work if the first parameter is of f() is s const reference, as temporary objects like the result of a + b can only be bound to const references.
In C or C++, as long as x and y are not pointers (in which case the expression is not useful anyway), they are both evaluated before the function call and the VALUE of the result is pushed on the stack. There are no references involved, at all.
All parameters in C and C++ are always passed by value. If a reference type (eg int*, int&) is passed to the function, the VALUE of the reference is passed. While the referenced object may be changed by accessing eg *x within the function, the value of the reference still cannot be changed, because C and C++ parameters are always always always passed by value only.
EDIT: an exception in C and C++ is the case in which some overloaded operator is defined like the following:
T* operator+ (L lhs, R rhs) {return new T(lhs, rhs);}
and x is an L, and y is an R. In this case, the value of the T* generated by the function is pushed on the stack as a parameter. Don't write code like that, it confuses other programmers =D.

Pass by reference or pass by value? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
When learning a new programming language, one of the possible roadblocks you might encounter is the question whether the language is, by default, pass-by-value or pass-by-reference.
So here is my question to all of you, in your favorite language, how is it actually done? And what are the possible pitfalls?
Your favorite language can, of course, be anything you have ever played with: popular, obscure, esoteric, new, old...
Here is my own contribution for the Java programming language.
first some code:
public void swap(int x, int y)
{
int tmp = x;
x = y;
y = tmp;
}
calling this method will result in this:
int pi = 3;
int everything = 42;
swap(pi, everything);
System.out.println("pi: " + pi);
System.out.println("everything: " + everything);
"Output:
pi: 3
everything: 42"
even using 'real' objects will show a similar result:
public class MyObj {
private String msg;
private int number;
//getters and setters
public String getMsg() {
return this.msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public int getNumber() {
return this.number;
}
public void setNumber(int number) {
this.number = number;
}
//constructor
public MyObj(String msg, int number) {
setMsg(msg);
setNumber(number);
}
}
public static void swap(MyObj x, MyObj y)
{
MyObj tmp = x;
x = y;
y = tmp;
}
public static void main(String args[]) {
MyObj x = new MyObj("Hello world", 1);
MyObj y = new MyObj("Goodbye Cruel World", -1);
swap(x, y);
System.out.println(x.getMsg() + " -- "+ x.getNumber());
System.out.println(y.getMsg() + " -- "+ y.getNumber());
}
"Output:
Hello world -- 1
Goodbye Cruel World -- -1"
thus it is clear that Java passes its parameters by value, as the value for pi and everything and the MyObj objects aren't swapped.
be aware that "by value" is the only way in java to pass parameters to a method. (for example a language like c++ allows the developer to pass a parameter by reference using '&' after the parameter's type)
now the tricky part, or at least the part that will confuse most of the new java developers: (borrowed from javaworld)
Original author: Tony Sintes
public void tricky(Point arg1, Point arg2)
{
arg1.x = 100;
arg1.y = 100;
Point temp = arg1;
arg1 = arg2;
arg2 = temp;
}
public static void main(String [] args)
{
Point pnt1 = new Point(0,0);
Point pnt2 = new Point(0,0);
System.out.println("X: " + pnt1.x + " Y: " +pnt1.y);
System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);
System.out.println(" ");
tricky(pnt1,pnt2);
System.out.println("X: " + pnt1.x + " Y:" + pnt1.y);
System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);
}
"Output
X: 0 Y: 0
X: 0 Y: 0
X: 100 Y: 100
X: 0 Y: 0"
tricky successfully changes the value of pnt1!
This would imply that Objects are passed by reference, this is not the case!
A correct statement would be: the Object references are passed by value.
more from Tony Sintes:
The method successfully alters the
value of pnt1, even though it is
passed by value; however, a swap of
pnt1 and pnt2 fails! This is the major
source of confusion. In the main()
method, pnt1 and pnt2 are nothing more
than object references. When you pass
pnt1 and pnt2 to the tricky() method,
Java passes the references by value
just like any other parameter. This
means the references passed to the
method are actually copies of the
original references. Figure 1 below
shows two references pointing to the
same object after Java passes an
object to a method.
(source: javaworld.com)
Conclusion or a long story short:
Java passes it parameters by value
"by value" is the only way in java to pass a parameter to a method
using methods from the object given as parameter will alter the object as the references point to the original objects. (if that method itself alters some values)
useful links:
http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html
http://www.ibm.com/developerworks/java/library/j-passbyval/
http://www.ibm.com/developerworks/library/j-praxis/pr1.html
http://javadude.com/articles/passbyvalue.htm
Here is another article for the c# programming language
c# passes its arguments by value (by default)
private void swap(string a, string b) {
string tmp = a;
a = b;
b = tmp;
}
calling this version of swap will thus have no result:
string x = "foo";
string y = "bar";
swap(x, y);
"output:
x: foo
y: bar"
however, unlike java c# does give the developer the opportunity to pass parameters by reference, this is done by using the 'ref' keyword before the type of the parameter:
private void swap(ref string a, ref string b) {
string tmp = a;
a = b;
b = tmp;
}
this swap will change the value of the referenced parameter:
string x = "foo";
string y = "bar";
swap(x, y);
"output:
x: bar
y: foo"
c# also has a out keyword, and the difference between ref and out is a subtle one.
from msdn:
The caller of a method which takes an
out parameter is not required to
assign to the variable passed as the
out parameter prior to the call;
however, the callee is required to
assign to the out parameter before
returning.
and
In contrast ref parameters are
considered initially assigned by the
callee. As such, the callee is not
required to assign to the ref
parameter before use. Ref parameters
are passed both into and out of a
method.
a small pitfall is, like in java, that objects passed by value can still be changed using their inner methods
conclusion:
c# passes its parameters, by default, by value
but when needed parameters can also be passed by reference using the ref keyword
inner methods from a parameter passed by value will alter the object (if that method itself alters some values)
useful links:
http://msdn.microsoft.com/en-us/vcsharp/aa336814.aspx
http://www.c-sharpcorner.com/UploadFile/saragana/Willswapwork11162005012542AM/Willswapwork.aspx
http://en.csharp-online.net/Value_vs_Reference
Python uses pass-by-value, but since all such values are object references, the net effect is something akin to pass-by-reference. However, Python programmers think more about whether an object type is mutable or immutable. Mutable objects can be changed in-place (e.g., dictionaries, lists, user-defined objects), whereas immutable objects can't (e.g., integers, strings, tuples).
The following example shows a function that is passed two arguments, an immutable string, and a mutable list.
>>> def do_something(a, b):
... a = "Red"
... b.append("Blue")
...
>>> a = "Yellow"
>>> b = ["Black", "Burgundy"]
>>> do_something(a, b)
>>> print a, b
Yellow ['Black', 'Burgundy', 'Blue']
The line a = "Red" merely creates a local name, a, for the string value "Red" and has no effect on the passed-in argument (which is now hidden, as a must refer to the local name from then on). Assignment is not an in-place operation, regardless of whether the argument is mutable or immutable.
The b parameter is a reference to a mutable list object, and the .append() method performs an in-place extension of the list, tacking on the new "Blue" string value.
(Because string objects are immutable, they don't have any methods that support in-place modifications.)
Once the function returns, the re-assignment of a has had no effect, while the extension of b clearly shows pass-by-reference style call semantics.
As mentioned before, even if the argument for a is a mutable type, the re-assignment within the function is not an in-place operation, and so there would be no change to the passed argument's value:
>>> a = ["Purple", "Violet"]
>>> do_something(a, b)
>>> print a, b
['Purple', 'Violet'] ['Black', 'Burgundy', 'Blue', 'Blue']
If you didn't want your list modified by the called function, you would instead use the immutable tuple type (identified by the parentheses in the literal form, rather than square brackets), which does not support the in-place .append() method:
>>> a = "Yellow"
>>> b = ("Black", "Burgundy")
>>> do_something(a, b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in do_something
AttributeError: 'tuple' object has no attribute 'append'
Since I haven't seen a Perl answer yet, I thought I'd write one.
Under the hood, Perl works effectively as pass-by-reference. Variables as function call arguments are passed referentially, constants are passed as read-only values, and results of expressions are passed as temporaries. The usual idioms to construct argument lists by list assignment from #_, or by shift tend to hide this from the user, giving the appearance of pass-by-value:
sub incr {
my ( $x ) = #_;
$x++;
}
my $value = 1;
incr($value);
say "Value is now $value";
This will print Value is now 1 because the $x++ has incremented the lexical variable declared within the incr() function, rather than the variable passed in. This pass-by-value style is usually what is wanted most of the time, as functions that modify their arguments are rare in Perl, and the style should be avoided.
However, if for some reason this behaviour is specifically desired, it can be achieved by operating directly on elements of the #_ array, because they will be aliases for variables passed into the function.
sub incr {
$_[0]++;
}
my $value = 1;
incr($value);
say "Value is now $value";
This time it will print Value is now 2, because the $_[0]++ expression incremented the actual $value variable. The way this works is that under the hood #_ is not a real array like most other arrays (such as would be obtained by my #array), but instead its elements are built directly out of the arguments passed to a function call. This allows you to construct pass-by-reference semantics if that would be required. Function call arguments that are plain variables are inserted as-is into this array, and constants or results of more complex expressions are inserted as read-only temporaries.
It is however exceedingly rare to do this in practice, because Perl supports reference values; that is, values that refer to other variables. Normally it is far clearer to construct a function that has an obvious side-effect on a variable, by passing in a reference to that variable. This is a clear indication to the reader at the callsite, that pass-by-reference semantics are in effect.
sub incr_ref {
my ( $ref ) = #_;
$$ref++;
}
my $value = 1;
incr(\$value);
say "Value is now $value";
Here the \ operator yields a reference in much the same way as the & address-of operator in C.
There's a good explanation here for .NET.
A lot of people are surprise that reference objects are actually passed by value (in both C# and Java). It's a copy of a stack address. This prevents a method from changing where the object actually points to, but still allows a method to change the values of the object. In C# its possible to pass a reference by reference, which means you can change where an actual object points to.
Don't forget there is also pass by name, and pass by value-result.
Pass by value-result is similar to pass by value, with the added aspect that the value is set in the original variable that was passed as the parameter. It can, to some extent, avoid interference with global variables. It is apparently better in partitioned memory, where a pass by reference could cause a page fault (Reference).
Pass by name means that the values are only calculated when they are actually used, rather than at the start of the procedure. Algol used pass-by-name, but an interesting side effect is that is it very difficult to write a swap procedure (Reference). Also, the expression passed by name is re-evaluated each time it is accessed, which can also have side effects.
Whatever you say as pass-by-value or pass-by-reference must be consistent across languages. The most common and consistent definition used across languages is that with pass-by-reference, you can pass a variable to a function "normally" (i.e. without explicitly taking address or anything like that), and the function can assign to (not mutate the contents of) the parameter inside the function and it will have the same effect as assigning to the variable in the calling scope.
From this view, the languages are grouped as follows; each group having the same passing semantics. If you think that two languages should not be put in the same group, I challenge you to come up with an example that distinguishes them.
The vast majority of languages including C, Java, Python, Ruby, JavaScript, Scheme, OCaml, Standard ML, Go, Objective-C, Smalltalk, etc. are all pass-by-value only. Passing a pointer value (some languages call it a "reference") does not count as pass by reference; we are only concerned about the thing passed, the pointer, not the thing pointed to.
Languages such as C++, C#, PHP are by default pass-by-value like the languages above, but functions can explicitly declare parameters to be pass-by-reference, using & or ref.
Perl is always pass-by-reference; however, in practice people almost always copy the values after getting it, thus using it in a pass-by-value way.
by value
is slower than by reference since the system has to copy the parameter
used for input only
by reference
faster since only a pointer is passed
used for input and output
can be very dangerous if used in conjunction with global variables
Concerning J, while there is only, AFAIK, passing by value, there is a form of passing by reference which enables moving a lot of data. You simply pass something known as a locale to a verb (or function). It can be an instance of a class or just a generic container.
spaceused=: [: 7!:5 <
exectime =: 6!:2
big_chunk_of_data =. i. 1000 1000 100
passbyvalue =: 3 : 0
$ y
''
)
locale =. cocreate''
big_chunk_of_data__locale =. big_chunk_of_data
passbyreference =: 3 : 0
l =. y
$ big_chunk_of_data__l
''
)
exectime 'passbyvalue big_chunk_of_data'
0.00205586720663967
exectime 'passbyreference locale'
8.57957102144893e_6
The obvious disadvantage is that you need to know the name of your variable in some way in the called function. But this technique can move a lot of data painlessly. That's why, while technically not pass by reference, I call it "pretty much that".
PHP is also pass by value.
<?php
class Holder {
private $value;
public function __construct($value) {
$this->value = $value;
}
public function getValue() {
return $this->value;
}
}
function swap($x, $y) {
$tmp = $x;
$x = $y;
$y = $tmp;
}
$a = new Holder('a');
$b = new Holder('b');
swap($a, $b);
echo $a->getValue() . ", " . $b->getValue() . "\n";
Outputs:
a b
However in PHP4 objects were treated like primitives. Which means:
<?php
$myData = new Holder('this should be replaced');
function replaceWithGreeting($holder) {
$myData->setValue('hello');
}
replaceWithGreeting($myData);
echo $myData->getValue(); // Prints out "this should be replaced"
By default, ANSI/ISO C uses either--it depends on how you declare your function and its parameters.
If you declare your function parameters as pointers then the function will be pass-by-reference, and if you declare your function parameters as not-pointer variables then the function will be pass-by-value.
void swap(int *x, int *y); //< Declared as pass-by-reference.
void swap(int x, int y); //< Declared as pass-by-value (and probably doesn't do anything useful.)
You can run into problems if you create a function that returns a pointer to a non-static variable that was created within that function. The returned value of the following code would be undefined--there is no way to know if the memory space allocated to the temporary variable created in the function was overwritten or not.
float *FtoC(float temp)
{
float c;
c = (temp-32)*9/5;
return &c;
}
You could, however, return a reference to a static variable or a pointer that was passed in the parameter list.
float *FtoC(float *temp)
{
*temp = (*temp-32)*9/5;
return temp;
}