1

Some languages like Racket don't need a return statement to give the caller back a value. For example:

(define (myfunc)
    (1))

Why do other languages such as C# have an explicit return keyword? Is there a real use for this keyword, or is it just for more clarity?

rookie
  • 2,783
  • 5
  • 29
  • 43

2 Answers2

2

This is typical of functional languages where the function returns the last evaluated expression.

In an imperative context, this is an impractical restriction, since it is common to return early, for example when seeing if an array contains a certain element

contains(array, element) {
  for(el in array) {
    if(el == element) return true;
  }
  return false;
}

whereas in a functional context you would accomplish this with recursion

(define (contains array element)
  (cond
    ((empty? array) false)
    ((eq (head array) element) true)
    (else (contains (tail array) element))))
Peter Olson
  • 139,199
  • 49
  • 202
  • 242
0

Your question is somewhat related to the difference between a function and a procedure. Functional programing languages support only functions because they promote the paradigm of writing your code in a "functional way" ,meaning, no side effects, which means that you should always return something (the result).

That doesn't mean that you can't write non-functional code in a functional-programing language, Scheme, for example, has !set. That said - it is not encouraged to use it because of its a non-functional pattern.

Community
  • 1
  • 1
Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129