Difference between a function and procedure? - iphone

I had a doubt
I know that main difference between a function and procedure is
The function compulsory returns a value where as a procedure may or may not returns value.
But when we use a function of type void it returns nothing.
Can u people please clarify my doubt.

Traditionally, a procedure returning a value has been called a function (see below), however, many modern languages dispense with the term procedure altogether, preferring to use the term function for all named code blocks.
Read more at Suite101: Procedure, subroutine or function?: Programming terminology 101 - a look at the differences in approach and definition of procedures, subroutines and functions. http://www.suite101.com/content/procedure--subroutine-or-function--a8208#ixzz1GqkE7HjE

In C and its derivatives, the term "procedure" is rarely used. C has functions some of which return a value and some of which don't. I think this is an artefact of C's heritage where before the introduction of void in ANSI C, there was no way to not return a value. By default functions returned an int which you could ignore (can still) and might be some random number if no explicit return value was specified.
In the Pascal language family, the difference is explicit, functions return a value and procedures don't. A different keyword is used in each case for the definition. Visual Basic also differentiates with functions and subroutines(?).
Since we are talking about Objective-C, there are some further issues to confuse you. Functions associated with a class or object are known as "methods" (class methods and instance methods respectively).
Also, if we are being pedantic, you don't call Objective-C methods, you invoke them by sending a message to the object. The distinction is actually quite important because the message name (aka "selector") does not necessarily always refer to the same method, it can be changed at run time. This is fundamentally different to languages like Java and C++ where a particular method name for a particular class is really just a symbolic name for the address of the block of code constituting the body of the method.

Depending on the programming language, the distinction may be not so clear. Let's take a conservative language, Pascal:
procedure indeed has no return value. It is used for operations which do not have a return value, or have multiple return values. In the latter case, multiple arguments (the return-arguments or output-arguments) are passed by reference (using the var keyword) and their values are directly modified from inside the procedure. (Note that this latter case may not be considered good practice, depending on the circumstances).
function has a single return value, and usually we do not expect it to change the value of any of its arguments (which arguments may then be passed by value, or via the const keyword). Multiple return values may be returned by bundling them into a record.
C or Java does not distinguish syntactically, so a function of return type void can be thought of as a procedure. Scala distinguished between them by the presence of an equals sign between the method head and method body.
Generally, no matter how an actual language calls its construct, we would ideally expect that
A function takes arguments, doesn't modify any state (like mutating arguments, global variables, or printing info for the user to the console), and returns the result of computation.
A procedure takes arguments, performs operations which can have side-effects (writing to a database, printing to the console, maybe mutating variables), but hopefully doesn't mutate any arguments.
In practice however, depending on the situation, blends of these expectations can be observed. Sticking to these guidelines helps I think.

Related

What is the difference in atomic_load() and assignment?

I am working on a project that deals with lots of atomic operations. Till now I didn’t knew about atomic_load() and was only relying on assignment operator to get value of an atomic type and I haven’t seen an error except of so much of testing. Those atomic types are changed by multiple processes and threads as well by atomic_compare_exchange_strong_explicit(), so they will need an old value every time, and that’s where I always did oldValue = <Atomic_ type_variable> and it always works fine.
Is that just by chance? Should I prefer using atomic_load()?
foo = atomic_var is just a shortcut syntax for foo = atomic_load(&atomic_var);
Which itself is a shortcut for foo = atomic_load_explicit(&atomic_var, memory_order_seq_cst); That has a use-case when you want to use an ordering weaker than the default seq_cst.
The main reason for using atomic_load explicitly in your source code is probably to remind human readers that a variable or pointer is atomic. Or maybe as a part of a macro, using atomic_load(&(macro_input)) would create a compile-time error for a non-atomic pointer.
As a "generic" function, you can't take a normal function-pointer to it.
Its existence may be just to make it easier to write the language standard, and explain everything in terms of functions.
It's not the actual assignment that's key here, it's evaluating the atomic variable in an rvalue context (reading it's value as part of an expression, like you typically find on the right-hand side of an =). printf("%d\n", my_atomic_var); is also equivalent to atomic_load.
And BTW, the same thing holds for atomic_var = foo; being exactly the same as atomic_store_explicit with mo_seq_cst. Here it is assignment that's key.
Other kinds of lvalue references to an atomic variable are different, like read-modify-write atomic_var++ is equivalent to atomic_fetch_add.

What's the point behind passing functions as arguments to other functions?

It's a rather general purpose question and not specific to any one language. I don't quite understand the point behind passing a function as an argument to another function. I understand that if a function, say, foo1() needs to use some result returned by another function foo2(), why can't the values returned/updated by foo2() be passed to foo1() as is? Or in another scenario, why can't the foo2() be called within foo1() with its results being used therein?
Also what happens under the hood when a foo2() is passed as an argument to foo1()? Is foo2() executed prior to foo1()?
Generally speaking, you pass a function foo2 to a function foo1 in cases where multiple evaluations of foo2 will be necessary - and you perhaps don't know in advance what parameters will be used for each call of foo2, so you couldn't possibly perform the calls yourself in advance.
I think that a sort() function/method on lists might be the best concrete example. Consider a list of People - you might reasonably want to sort them alphabetically by name, or numerically by age, or by geographical distance from a given point, or many other possible orders. It would hardly be practical to include every such ordering as built-in options to sort(): the usual approach taken by languages is to allow the caller to provide a function as a parameter, that defines the ordering between items of the list.
There are many reasons:
Dependency injection: if you pass a method that in production will use a database call, and you use it with different parameters, you could substitute it with some mock when unit testing.
Map, filter, reduce: you could apply the same method to a list of parameters, to map it, filter it or reduce it.
Usually to provide callbacks, or to separate interface from implementation. Look up the following:
1. Dependency Injection,
2. Callbacks,
3. Anonymous Functions (aka Lambdas),
4. PIMPL
etc
Take a look at this book where it is used extensively in developing TDD with C:
https://www.amazon.co.uk/Driven-Development-Embedded-Pragmatic-Programmers/dp/193435662X

Is it a pure function if it reads some data from outside rather than parameters?

In the book of "functional programming in Scala", it gives some examples about side-effects, like:
Modifying a variable
Modifying a data structure in place
Setting a field on an object
Throwing an exception or halting with an error  Printing to the console or reading user input
Reading from or writing to a file
Drawing on the screen
My question is, is reading some data from outside rathen than the parameters makes the function impure?
E.g.
val name = "Scala"
def upcase() = name.toUpperCase
Is the upcase function pure or not?
Edit: as per this answer: https://stackoverflow.com/a/31377452/342235, my "function" is not actually function, it's a method, so I give a function version of it, and ask the same question:
val name = "Scala"
val upcase: () => String = () => name.toUpperCase
Reading from immutable data is not impure; the function will still return the same value every time. If name were a var then that function would be impure, since something external could change name, so multiple calls to upcase() might evaluate to different values.
(Of course it might be possible to e.g. alter name through reflection. Properly we can only talk about purity with respect to some notion of what kind of functions are allowed to call a given function, and what kind of side effects we consider to be equivalent)
It's worth noting that your function is not pure because toUpperCase is not pure; it depends on the system's default Locale, and may produce different results on different systems (e.g. on a Turkish system, "i".toUpperCase == "İ"). You should always pass an explicit Locale, e.g. def upcase() = name.toUpperCase(Locale.ENGLISH); then the function will be pure.
Interestingly, the answer is "No", but not for the reason you think it is. Your upcase is not a pure function. It is, however, pure, but it is a method, not a function.

Can we say that using "pass by reference" is always better than "pass by value"?

In C# or php or other languages, there are 2 ways to pass a value to a function, pass it by value and pass it by referece.
Pass parameter by value make the value copied in the function, so this need a extra memory space although the memory space will be reclaimed after running outside the function.
But passing parameter by reference no need to copy a value, it's save the memory. From this perspective, can we say that using "pass by reference" is always better than "pass by value"?
Pass by reference and pass by value are semantically different and sometimes one is correct approach and sometimes the other one is. In many cases the task at hand already prescribes which approach is needed and in contexts where only one option is supported you often need to manually work around it (e.g., if you need a copy in Java you'll need to clone() the object).
In the context of generic functions the answer is rather the opposite way of your proposed preference: pass arguments of deduced type by value! The reason is that you can use something like std::ref() to obtain reference semantics but there is no way to get value semantics if the functions use reference semantics.
No.
There are tons of cases where you'd want to pass by value.
An example might be when you need both const Type& and Type&& overloads. Passing by value just handles both cases without having to duplicate any code:
void function(Object o) { do_something_with(std::move(o)); }
As opposed to:
void function(Object&& o) { do_something_with(std::move(o)); }
void function(const Object& o) { do_something_with(Object(o)); }
Of course there is much more to the subject, but since you're only asking for "is it always better?" I feel a single disproving example is enough. ;)
Edit: the question was originally tagged c++ hence my very specific answer.
Another, more language-agnostic example would be when you need to make a copy of your parameter because you don't want to modify the original object:
void function(int& val) { int v2 = val; modify(v2); use(v2); }
// vs
void function(int val) { modify(val); use(val); }
You get the idea...
Pass by reference requires copying a reference to the object. If that reference is comparable in cost to the object itself, then the benefit is illusory. Also, sometimes you need a copy of the object, and passing by value provides you one.
Also, there's a key error in the reasoning in the question. If passing by value, and there is no need to copy the value, nothing requires that the value actually be copied. Most languages have an "as-if" rule that states that the program only has to act as if the compiler did what you ask for. So if the copy can be avoided, the compiler is free to avoid it. If the copy can't be avoided, then you needed the copy.

Why making a difference between methods and functions in Scala?

I have been reading about methods and functions in Scala. Jim's post and Daniel's complement to it do a good job of explaining what the differences between these are. Here is what I took with me:
functions are objects, methods are not;
as a consequence functions can be passed as argument, but methods can not;
methods can be type-parametrised, functions can not;
methods are faster.
I also understand the difference between def, val and var.
Now I have actually two questions:
Why can't we parametrise the apply method of a function to parametrise the function? And
Why can't the method be called by the function object to run faster? Or the caller of the function be made calling the original method directly?
Looking forward to your answers and many thanks in advance!
1 - Parameterizing functions.
It is theoretically possible for a compiler to parameterize the type of a function; one could add that as a feature. It isn't entirely trivial, though, because functions are contravariant in their argument and covariant in their return value:
trait Function1[+T,-R] { ... }
which means that another function that can take more arguments counts as a subclass (since it can process anything that the superclass can process), and if it produces a smaller set of results, that's okay (since it will also obey the superclass construct that way). But how do you encode
def fn[A](a: A) = a
in that framework? The whole point is that the return type is equal to the type passed in, whatever that type has to be. You'd need
Function1[ ThisCanBeAnything, ThisHasToMatch ]
as your function type. "This can be anything" is well-represented by Any if you want a single type, but then you could return anything as the original type is lost. This isn't to say that there is no way to implement it, but it doesn't fit nicely into the existing framework.
2 - Speed of functions.
This is really simple: a function is the apply method on another object. You have to have that object in order to call its method. This will always be slower (or at least no faster) than calling your own method, since you already have yourself.
As a practical matter, JVMs can do a very good job inlining functions these days; there is often no difference in performance as long as you're mostly using your method or function, not creating the function object over and over. If you're deeply nesting very short loops, you may find yourself creating way too many functions; moving them out into vals outside of the nested loops may save time. But don't bother until you've benchmarked and know that there's a bottleneck there; typically the JVM does the right thing.
Think about the type signature of a function. It explicitly says what types it takes. So then type-parameterizing apply() would be inconsistent.
A function is an object, which must be created, initialized, and then garbage-collected. When apply() is called, it has to grab the function object in addition to the parent.