2026a
# foldr
从右往左使用函数组合(折叠)向量
函数库: TySymbolicMath
# 语法
foldr(op, itr)
foldr(op, itr; init=0)
# 说明
foldr(op,itr) 使用 op 折叠 itr。 即 foldr 对 ltr 的前两个元素调用 fun ,然后对结果和下一个元素反复调用 fun ,直到最后一个元素被合并。 以编程方式,折叠操作是 foldr(op,itr) = op(foldr(fun,itr[1:end-1]),itr[end])。示例
如果 itr 为空,则 foldr(op, itr; init=0) 返回值 init。示例
# 示例
使用函数折叠向量
using TySymbolicMath
@variables a b c d
4-element Vector{Num}:
a
b
c
d
foldr(Jacobi.am,[a,b,c,d])
ans = TyMath.Jacobi.am(a, TyMath.Jacobi.am(b, TyMath.Jacobi.am(c, d)))
foldr(^,[a,b,c,d])
ans = a^(b^(c^d))
假设变量属于一组值
假设变量 x 属于一组值 1, 2, ..., 10 通过应用或条件 x == 1, ..., x == 10 使用 foldr。检查假设是通过使用假设来设置的。
using TySymbolicMath
@variables x
cond = foldr(|, x .== 1:10)
cond = (x == 1) | ((x == 2) | ((x == 3) | ((x == 4) | ((x == 5) | ((x == 6) | ((x == 7) | ((x == 8) | ((x == 9) | (x == 10)))))))))
指定折叠操作的默认值
通过指定第三个参数指定当输入为空时 fold 的默认值。如果未指定第三个参数且输入为空,则 fold 会引发错误。
创建函数对向量求和时,指定默认值 0,以便当向量为空时函数返回 0。
using TySymbolicMath
sumVector(x) = foldr(+, x, init = 0);
sumVector([])
ans = 0
# 输入参数
op - 用于折叠向量的函数函数
用于折叠向量的函数
itr - 要折叠的向量矢量 | 符号向量
要折叠的向量,指定为向量、符号向量。
数据类型: Int | Float | Num | Complex{Num}
复数支持: 是
init - 折叠操作的默认值矢量 | 符号向量
折叠操作初始默认值,指定为矢量或符号向量
数据类型: Int | Float | Num | Complex{Num}
复数支持: 是