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

For example, how to write the function g = (xy) / (xz)? I know how to write a function with two parameters.

+4
source share
1 answer

One way is to use variable mapping:

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 consider your variables as an array vx y zand define your function as a series of operations with arrays. For instance:

  • 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 do it too far and write:

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

but you probably shouldn't do that.

+4
source

Source: https://habr.com/ru/post/1686549/


All Articles