Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass function as an argument in APL

How do I pass a function as an argument?

The basic idea is something like this (which doesn't work):

∇R ← double a
R ← 2 × a
∇

∇R ← a applytwice f
R ← f f a
∇

5 applytwice double

Is there something like \fun in erlang or function-pointers in C?

like image 742
Hyperboreus Avatar asked Nov 07 '13 20:11

Hyperboreus


People also ask

How do you pass an argument to a function?

Arguments are passed by value; that is, when a function is called, the parameter receives a copy of the argument's value, not its address. This rule applies to all scalar values, structures, and unions passed as arguments. Modifying a parameter does not modify the corresponding argument passed by the function call.

How do you define a function in APL?

Unlike many programming languages which use parentheses or brackets for function calls, function application in APL is written simply by writing the function next to its arguments.

Why would you pass a function as an argument?

Because functions are objects we can pass them as arguments to other functions. Functions that can accept other functions as arguments are also called higher-order functions. In the example below, a function greet is created which takes a function as an argument.


1 Answers

In APL, functions may not be passed as arguments to functions. However, APL has operators, which are higher order functions, that can take functions as arguments. There are primitive operators like / (reduction) used for example to sum up a vector +/v. The function + is the left operand and is passed into the operator /.

In Dyalog APL, there is a primitive operator using the (named "power") for apply a function n times so we can write:

      double←{2×⍵}
      (double ⍣ 2) 7
28
      (double ⍣ 10) 7
7168

You can also write your own operators (in most APLs). In Dyalog APL we can write your applytwice operator as:

     applytwice←{⍺⍺ ⍺⍺ ⍵}
     double applytwice 7
28

Finally, you can pass functions around by putting them in a namespace and passing the namespace around instead. This is like a very light weight instance of class with a method. For example:

       s←⎕NS ''
       s.f←{2×⍵}
       ApplyFTwice←{⍺.f ⍺.f ⍵}
       s ApplyFTwice 7
28

In this case, the function has to be named f, but we could many different functions named f, each in its own namespace.

like image 159
Paul Mansour Avatar answered Oct 07 '22 04:10

Paul Mansour