logo

Programming Languages - Functions, Methods, Macros

Function vs Method vs Procedure vs Macro

  • functions vs macros:
    • Macros are executed at compile time. They generally expand into new pieces of code that the compiler will then need to further process. Functions get called at runtime.
    • In macro, you can take variable number of parameters. In function you have to define number and type of parameters.
  • functions vs procedures:
    • functions return values; procedures do not return any value.
  • functions vs methods:
    • a method is a function that belongs to a class.

Macros

Macros are a way of writing code that writes other code, which is known as metaprogramming.

Naming Convention:

  • C is SCREAMING_SNAKE_CASE
  • Rust: macros are named snake_case!, e.g. println!, vec!, panic!

Go

Function values may be used as function arguments and return values.

func compute(fn func(float64, float64) float64) float64 {
	return fn(3, 4)
}

func main() {
  hypot := func(x, y float64) float64 {
		return math.Sqrt(x*x + y*y)
	}
  fmt.Println(compute(hypot))
}

Go functions may be closures:

func adder() func(int) int {
	sum := 0
	return func(x int) int {
		sum += x
		return sum
	}
}

func main() {
	pos, neg := adder(), adder()
	for i := 0; i < 10; i++ {
		fmt.Println(
			pos(i),
			neg(-2*i),
		)
	}
}

JavaScript

Set default value inside function

function foo(params) {
  var settings = params || {};
}

Higher Order Functions and First-class functions

Higher order functions: functions that either take functions as parameters, or return functions.

First-class functions: functions that are treated as values; i.e. the functions can be assigned to a variable and can be passed around as an argument.

        Higher Order Functions
                ^
                |
function = function(function)
   |                  |
   v                  v
   first class function

C++

Since C++11, we can use std::function as an argument or the returned result.

Java

Before Java 8, use anonymous inner classes; after Java 8, we can pass the function as an argument:

Collections.sort(list, (String a, String b) -> {
    return a.compareTo(b);
});

Python

Use decorators:

@foo
def bar():
    pass

It's equivelent to:

def bar():
    pass
# Pass bar() to foo() as an argument
bar = foo(bar)