How to write a function with more than 3 parameters in J?

Viewed 109

For example, how to write the function g=(x-y)/(x-z)? I know how to write the function with 2 parameters.

1 Answers

One way is to use variable matching:

f =: 3 : 0
'x y z' =. y
(x-y)%(x-z)
)

f 1; 2; 3
0.5
f 1 2 3 
0.5
f 1.5; 2; 0.5
_0.5

Another way is to treat your variables as an array v -> x y z and define your function as a series of array operations. For example:

  • multiply and add +/ 1 _1 0 * x y z,
  • multiply and add +/ 1 0 _1 * x y z,
  • divide %/

This can be written as:

g =: 3 :'%/ F (+/ . *) y'

where F is

1 _1  0
1  0 _1

:

g 1 2 3 
0.5
g 1.5 2 0.5
_0.5

You can take this too far and write:

 h =: 3 : '((0{y) - (1{y))  % ((0{y) - (2{y))'

but you probably shouldn't.

Related