Skip to content

Notes on Function Calls

Daniel edited this page May 7, 2019 · 3 revisions

Functions

// a function with 4 arguments
f1 := func(a, b, c, d) {}

// a function with 3 arguments including a variadic argument 'c'
f2 := func(a, b, c...) {}

Function Calls

f1(1, 2, 3, 4)    // ok
f1(1, 2, 3)       // illegal
f1(1, 2, 3, 4, 5) // illegal

f2(1)             // illegal
f2(1, 2)          // ok: c = []
f2(1, 2, 3)       // ok: c = [3]
f2(1, 2, 3, 4)    // ok: c = [3, 4]

Function Calls with Spread Syntax

a := [1, 2, 3] 
f1(a...)          // error: f1(1, 2, 3)
f1(1, a...)       // ok: f1(1, 1, 2, 3)

f2(a...)          // ok: a = 1, b = 2, c = [3]
f2(1, a...)       // ok: a = 1, b = 1, c = [2, 3]
f2(1, 2, a...)    // ok: a = 1, b = 2, c = [1, 2, 3]

Some Examples

each := func(x, f) {
  for k, v in x { f(k, v) }
}

each([1, 2, 3], func(_, v) {
  print(v)
})

bind := func(f, a...) {
  return func(b...) {
    return f([a..., b...]...)
  }
}

obj := {
  n: 0,
  inc: func(self, d) {
    self.n += d
  }
}

a := new(obj)   // new builtin
a.inc(10)       // a.n == 10
a.inc(4)        // a.n == 14

// 'new' builtin will be implemented in Go
// but it would look like this
new := func(proto) {
  instance := copy(proto)
  for k, v in proto {
    if is_function(v) {
      instance[k] = bind(instance, v)
    }
  }
}

Clone this wiki locally