英文:
In Dyalog APL, can an Reduce N-Wise be a function or is it just an expression?
问题
当我评估 2,/ 时,我希望得到一个类似这样的小型ASCII训练树:
-,/
┌┴┐
- /
┌─┘
,
看起来 2,/ 作为一个表达式可以工作,但不能作为一个可命名的函数,这是正确的吗?
英文:
Say I want to name a function (assign to a variable) that does n-wise (2 in this example) reduction. Using tryapl.org it looks like I can't:
v←⍳5
2,/v
┌───┬───┬───┬───┐
│1 2│2 3│3 4│4 5│
└───┴───┴───┴───┘
2,/
SYNTAX ERROR: Missing right argument
2,/
∧
When I evaluate 2,/ I expect to get a little ASCII train tree something like this:
-,/
┌┴┐
- /
┌─┘
,
It seems like 2,/ works as an expression but not as a nameable function -- is that right?
答案1
得分: 4
是的,但它必须形成两种模式之一:
- 一个3-列火叉
Agh - 带有绑定参数的函数
A∘g
一个3-列火叉 Agh
这是一个数组 A,一个函数 g,和一个函数 h,其中 h 被单子地应用于整体参数,而 g 被应用于 g 的结果,A 作为 g 的左参数。由于 ,/ 是与 2 作为左参数的二元函数,我们有一个额外的函数 h 对参数进行预处理。我们不需要任何预处理,所以我们使用一个恒等函数:
v←⍳5
f←2,/⊢
f
┌─┼──┐
2 ,/ ⊢
f v
┌───┬───┬───┬───┐
│1 2│2 3│3 4│4 5│
└───┴───┴───┴───┘
带有绑定参数的函数 A∘g
在这里,我们使用绑定运算符 ∘ 来将一个常数参数分别应用于一个二元函数。我们的常数是 2,而函数 g 是 ,/,但由于像 / 这样的运算符具有长的左作用域,2∘,/ 会被解析为 (2∘,)/,这不是我们想要的,所以我们必须将 ,/ 加括号:
v←⍳5
f←2∘(,/)
f
∘
┌┴┐
2 ,/
f v
┌───┬───┬───┬───┐
│1 2│2 3│3 4│4 5│
└───┴───┴───┴───┘
英文:
Yes, but it has to form one of two patterns:
- A 3-train (fork)
Agh - A function with a bound argument
A∘g
A 3-train (fork) Agh
This is an array A, a function g, and a function h, where h is applied monadically to the overall argument, and g is applied dyadically to the result of g, with A as g's left argument. Since ,/ is dyadic with the 2 as left argument, we have an extra function h pre-processing the argument. We don't need any pre-processing, so we use an identity function:
v←⍳5
f←2,/⊢
f
┌─┼──┐
2 ,/ ⊢
f v
┌───┬───┬───┬───┐
│1 2│2 3│3 4│4 5│
└───┴───┴───┴───┘
A function with a bound argument A∘g
Here, we use the Bind operator ∘ to curry a constant argument to a dyadic function. Our constant is 2 and the function g is ,/ but since operators like / have long left scope 2∘,/ would be parsed as (2∘,)/ which isn't what we want, so we have to parenthesise ,/:
v←⍳5
f←2∘(,/)
f
∘
┌┴┐
2 ,/
f v
┌───┬───┬───┬───┐
│1 2│2 3│3 4│4 5│
└───┴───┴───┴───┘
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论