2017-05-08

Some reflections on functions

Regular readers know my fascination for home computers. So, please take a look at the following small BASIC program:

10 PRINT "HELLO ";
20 GOSUB 70
30 FOR I = 1 TO 3
40 GOSUB 70
50 NEXT
60 END
70 PRINT "WORLD ";
80 RETURN

Screenshot taken from a emulated C64

In BASIC you can reuse code through so-called subroutines. They are invoked using the GOSUB keyword. END marks the end of the subroutine. As you can see in the above example, subroutines can be called from different parts of the program. However, subroutines are no functions, as they lack the ability to return a vlaue and to receive parameters. This is done as follows:

10 DEF FN POW2(X) = X * X
20 INPUT "PLEASE ENTER A NUMBER: "; A
30 PRINT FN POW2(A)

So, DEF FN defines a function, whereas FN invokes it.

JavaScript has the function keyword. It is used as follows:

function pow2(x) { return x * x; }

To invoke the function use something like pow2(3)

Swift is similar, but uses the func keyword:

func pow2(x: Double) -> Double { return x * x; }
print(pow2(x: 3.0))

Dart can be very terse:

pow2(x) => x * x;

Or more descriptive:

double pow2(double x) {
  return x * x;
}

Finally, Scheme:

(define pow2 (lambda (x) (* x x)))
(pow2 3)

What other language feature would you like to see compared? Feel free to suggest your favorites...

No comments:

Post a Comment