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

喜夏-厌秋 提交于 2019-12-12 12:14:10

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/46471661/how-to-write-a-function-with-more-than-3-parameters-in-j

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!