I'm new to functional languages and I was wondering why we can't pass a parameter by reference.
I found anserws saying that
you are not supposed to change the state of objects once they have been created
but I didn't quite get the idea.
It's not so much that you can't pass references, it's that with referential transparency there isn't a programmer-visible difference between references and values, because you aren't allowed to change what references point to. This makes it actually safer and more prevalent in pure functional programming to pass shared references around everywhere. From a semantic point of view, they may as well be values.
I think you have misunderstood the concept. Both Scheme and C/C++ are pass by value languages and most values are addresses (references).
Purely functional languages can have references and those are passed by value. What they don't have is redefining variables in the same scope (mutate bindings) and they don't have the possibility to update the object the reference points to. All operations return a fresh new object.
As an example I can give you Java's strings. Java is not purely functional but its strings are. If you change the string to uppercase you get a new string object in return and the original one has not been altered.
Most languages I know of are pass by value. Pass by name is alien to me.
Because if you pass params by reference you could change something in the parameter, which could introduce a side effect. Consider this:
function pay(person, cost) {
person.wallet -= cost;
}
function money(person) {
return person.wallet;
}
let joe = { name: "Joe", wallet: 300 };
console.log(money(joe)); // 300
pay(joe, 20);
console.log(money(joe)); // 280
The two money(joe) are taking the same input (the object joe) and giving different output (300, 280). This is in contradiction to the definition of a pure functional language (all functions must return the same output when given the same input).
If the program was made this way, there is no problem:
function pay(person, cost) {
return Object.freeze({ ...person, wallet: person.wallet - cost });
}
function money(person) {
return person.wallet;
}
let joe = Object.freeze({ name: "Joe", wallet: 300 });
console.log(money(joe)); // 300
let joe_with_less_money = pay(joe, 20);
console.log(money(joe)); // still 300
console.log(money(joe_with_less_money)); // 280
Here we have to fake pass-by-value by freezing objects (which makes them immutable) since JavaScript can pass parameters only one way (pass by sharing), but the idea is the same.
(This presupposes the implications of the term "pass-by-reference" that apply to languages like C++, where the implementation detail affects mutability, not the actual implementation detail of modern languages, where references are typically passed under the hood but immutability is assured by other means.)
i learned about tuples today, in a nutshell they allow you to store several values, an example of tupel is
let exampleTuple = (exampleString: "This", exampleInt: 1)
And we can easily access any value of a tuple with a dot notation, for example:
exampleTuple.exampleString
To me this seems extremely similar to objects holding certain information, I might be missing something or not understanding tuples completely, therefore I'm asking for an explanation on when we should use tuples or objects?
According to the book on Swift,
Tuples are useful for temporary groups of related values. They are not suited to the creation of complex data structures.
They define "temporary" through the scope of the data: if a piece of data never leaves the scope of a single method, or a group of methods of the same object, it can be considered temporary, even though it might very well persist through the lifetime of an application.
If your data structure is useful outside a temporary scope - for example, because it needs to be returned from a public method of your class, model it as a class or structure, rather than as a tuple.
Another important consideration is associating behavior with your data: if your object needs to have methods, use classes for them. Use tuples only for data devoid of behavior.
Tuples are heavily used in Python and it seems to me they have mostly the same purpose in Swift. Think of it as a quick way to deliver multiple values from one point to another. An example that shows up in the Swift book and a pattern that is used in Python very often is returning an HTTP status code and a text body from a method:
func greeting() {
return (200, "Hello World")
}
...
let (status, body) = greeting()
if 200 == status {
println(body)
}
else if status >= 400 {
println("Error \(status): \(body)")
}
Of course this is just one use case, but I think it gets the point across. A built-in example is the function enumerate(), which returns a tuple of (index, value):
for (idx, val) in enumerate(["a", "b", "c"]) {
println("Index \(idx): \(val)")
}
What languages provide the use of object literals? (Or in what languages could you easily emulate them?) Can you give a code example?
Starting with the obvious javascript snippet:
var someObj = {
someProperty: 123,
someFunction: function() {
alert('hello!');
}
};
Checkout C# anonymous types
var Customer = new
{
Company = "AgileApps",
Website = "http://www.agileapps.co.uk",
Name = "Big Al",
Entered = DateTime.Now
};
If you replace object by "term," then Prolog does this naturally (in fact, there's no other way to construct an object). Here's an example featuring binary trees:
% find a node in List with a nil left child and call its rightmost grandchild X
member(node(nil,node(_,X)), List).
Lisp and Scheme also have some pretty advances features in this area, particularly quoting and semiquoting:
;; construct right-leaning binary tree with x as the rightmost grandchild
`(nil . (nil . ,x))
Practically all functional programming languages have copied this in some form.
I found myself confronted with an interview question where the goal was to write a sorting algorithm that sorts an array of unsorted int values:
int[] unsortedArray = { 9, 6, 3, 1, 5, 8, 4, 2, 7, 0 };
Now I googled and found out that there are so many sorting algorithms out there!
Finally I could motivate myself to dig into Bubble Sort because it seemed pretty simple to start with.
I read the sample code and came to a solution looking like this:
static int[] BubbleSort(ref int[] array)
{
long lastItemLocation = array.Length - 1;
int temp;
bool swapped;
do
{
swapped = false;
for (int itemLocationCounter = 0; itemLocationCounter < lastItemLocation; itemLocationCounter++)
{
if (array[itemLocationCounter] > array[itemLocationCounter + 1])
{
temp = array[itemLocationCounter];
array[itemLocationCounter] = array[itemLocationCounter + 1];
array[itemLocationCounter + 1] = temp;
swapped = true;
}
}
} while (swapped);
return array;
}
I clearly see that this is a situation where the do { //work } while(cond) statement is a great help to be and prevents the use of another helper variable.
But is this the only case that this is more useful or do you know any other application where this condition has been used?
In general:
use do...while when you want the body to be executed at least once.
use while... when you may not want the body to be executed at all.
EDIT: I'd say the first option comes up about 10% of the time and the second about 90%. You can always re-factor to use either, in either circumstance. Use the one that's closest to what you want to say.
do...while guarantees that the body of code inside the loop executes at least once. This can be handy under certain conditions; when coding a REPL loop, for example.
Anytime you need to loop through some code until a condition is met is a good example of when to use do...while or while...
A good example of when to use do...while or while... is if you have a game or simulation where the game engine is continuously running the various components until some condition occurs like you win or lose.
Of course this is only one example.
The above posts are correct regarding the two conditional looping forms. Some languages have a repeat until form instead of do while. Also there's a minimalist view where only the necessary control structures should exist in a language. The while do is necessary but the do while isn't. And as for bubble sort you'll want to avoid going there as it's the slowest of the commonly known sorting algorithms. Look at selection sort or insertion sort instead. Quicksort and merge sort are fast but are hard to write without using recursion and perform badly if you happen to chose a poor pivot value.
I have read quite a few articles on closures, and, embarassingly enough, I still don't understand this concept! Articles explain how to create a closure with a few examples, but I don't see any point in paying much attention to them, as they largely look contrived examples. I am not saying all of them are contrived, just that the ones I found looked contrived, and I dint see how even after understanding them, I will be able to use them. So in order to understand closures, I am looking at a few real problems, that can be solved very naturally using closures.
For instance, a natural way to explain recursion to a person could be to explain the computation of n!. It is very natural to understand a problem like computing the factorial of a number using recursion. Similarly, it is almost a no-brainer to find an element in an unsorted array by reading each element, and comparing with the number in question. Also, at a different level, doing Object-oriented programming also makes sense.
So I am trying to find a number of problems that could be solved with or without closures, but using closures makes thinking about them and solving them easier. Also, there are two types to closures, where each call to a closure can create a copy of the environment variables, or reference the same variables. So what sort of problems can be solved more naturally in which of the closure implementations?
Callbacks are a great example. Let's take JavaScript.
Imagine you have a news site, with headlines and short blurbs and "Read More..." buttons next to each one. When the user clicks the button, you want to asynchronously load the content corresponding to the clicked button, and present the user with an indicator next to the requested headline so that the user can "see the page working at it".
function handleClickOnReadMore(element) {
// the user clicked on one of our 17 "request more info" buttons.
// we'll put a whirly gif next to the clicked one so the user knows
// what he's waiting for...
spinner = makeSpinnerNextTo(element);
// now get the data from the server
performAJAXRequest('http://example.com/',
function(response) {
handleResponse(response);
// this is where the closure comes in
// the identity of the spinner did not
// go through the response, but the handler
// still knows it, even seconds later,
// because the closure remembers it.
stopSpinner(spinner);
}
);
}
Alright, say you're generating a menu in, say, javascript.
var menuItems = [
{ id: 1, text: 'Home' },
{ id: 2, text: 'About' },
{ id: 3, text: 'Contact' }
];
And your creating them in a loop, like this:
for(var i = 0; i < menuItems.length; i++) {
var menuItem = menuItems[i];
var a = document.createElement('a');
a.href = '#';
a.innerHTML = menuItem.text;
// assign onclick listener
myMenu.appendChild(a);
}
Now, for the onclick listener, you might attempt something like this:
a.addEventListener('click', function() {
alert( menuItem.id );
}, false);
But you'll find that this will have every link alert '3'. Because at the time of the click, your onclick code is executed, and the value of menuItem is evaluated to the last item, since that was the value it was last assigned, upon the last iteration of the for loop.
Instead, what you can do is to create a new closure for each link, using the value of menuItem as it is at that point in execution
a.addEventListener('click', (function(item) {
return function() {
alert( item.id );
}
})( menuItem ), false);
So what's going on here? We're actually creating a function that accepts item and then immediately call that function, passing menuItem. So that 'wrapper' function is not what will be executed when you click the link. We're executing it immediately, and assigning the returned function as the click handler.
What happens here is that, for each iteration, the function is called with a new value of menuItem, and a function is returned which has access to that value, which is effectively creating a new closure.
Hope that cleared things up =)
Personally I hated to write sort routines when I had a list of objects.
Usually you had the sort function and a separate function to compare the two objects.
Now you can do it in one statement
List<Person> fList = new List<Person>();
fList.Sort((a, b) => a.Age.CompareTo(b.Age));
Well, after some time, spent with Scala, I can not imagine a code, operating on some list without closures. Example:
val multiplier = (i:Int) => i * 2
val list1 = List(1, 2, 3, 4, 5) map multiplier
val divider = (i:Int) => i / 2
val list2 = List(1, 2, 3, 4, 5) map divider
val map = list1 zip list2
println(map)
The output would be
List((2,0), (4,1), (6,1), (8,2), (10,2))
I'm not sure, if it is the example, you are looking for, but I personally think, that best examples of closures's real power can be seen on lists-examples: all kinds of sortings, searchings, iterating, etc.
I personally find massively helpful presentation by Stuart Langridge on Closures in JavaScript (slides in pdf). It's full of good examples and a bit of sense of humour as well.
In C#, a function can implement the concept of filtering by proximity to a point:
IEnumerable<Point> WithinRadius(this IEnumerable<Point> points, Point c, double r)
{
return points.Where(p => (p - c).Length <= r);
}
The lambda (closure) captures the supplied parameters and binds them up into a computation that will performed at some later time.
Well, I use Closures on a daily basis in the form of a function composition operator and a curry operator, both are implemented in Scheme by closures:
Quicksort in Scheme for instance:
(define (qsort lst cmp)
(if (null? lst) lst
(let* ((pivot (car lst))
(stacks (split-by (cdr lst) (curry cmp pivot))))
(append (qsort (cadr stacks) cmp)
(cons pivot
(qsort (car stacks) cmp))))))
Where I cmp is a binary function usually applied as (cmp one two), I curried it in this case to split my stack in two by creating a unitary predicate if you like, my curry operators:
(define (curry f . args)
(lambda lst (apply f (append args lst))))
(define (curryl f . args)
(lambda lst (apply f (append lst args))))
Which respectively curry righthanded and lefthanded.
So currying is a good example of closures, another example is functional composition. Or for instance a function which takes list and makes from that a predicate that tests if its argument is a member of that list or not, that's a closure too.
Closure is one of the power strengths of JavaScript, because JavaScript is a lambda language. For more on this subject go here:
Trying to simplify some Javascript with closures