I'm trying to use matrix algebra with the purpose of manipulating strings. This means being able to multiple matrix-like structures using concatenation and pasting of string or of arrays of strings.
I previously tried to implement the thing on R, but it was not possible as matrices can have only one dimensional entries.
I hope to be enough language-agnostic and abstract, but I'll use R-like code for sake of clarity. I should make explicit that I don't require real matrices, but matrix-like structure on which we can do matrices-like multiplication and retrieve the (ij) element of the structure.
{+,*} MATRICES MULTIPLICATION
两个n 维方阵A和B的 {+,*}-乘积是由以下元素定义的矩阵C: C i,j = Sum k=1,...,n A i,k * B k, Ĵ。
例如,考虑矩阵 M <- matrix(c(a,b,0,0,c,d,0,0,e),3,3)
。那么 M 乘以 M 就是 M <- matrix(c(a^2,a*b+b*c,b*d,0,c^2,c*d+d*e,0,0,e^2),3,3)
。
{c(,),paste0(,)} 矩阵乘法
我想实现的这个操作的规则与前面所说的乘法相同,其中的基本突变是总和应该是一个连接,而乘积应该是一个粘贴。换句话说,我们在前面的公式中找到a+b
,现在输出应该是“c(a,b)”,当我们找到 时a*b
,现在我们应该将其读为paste0(a,b)
。
必须尊重一些通常的属性,即分配属性和 0 元素属性。因此,如果a <- c("q",0,"w")
和b <- c("e")
然后a*b <- c("qe",0,"we")
(我们应该随意忘记 0 元素,将其删除,因为它不会影响计算。
此外,我们正在乘以等维矩阵,因此每个元素 C i,j = Sum k=1,...,n A i,k * B k,j现在被读作 c("A[i,1]B[1,j]",...,"A[i,n]B[n,j]")
。
最后,类似结果矩阵的结构应该是我们可以再次用于计算的东西(例如,进行更复杂的计算,如 mult(mult(A,B),C) 等等......)。
一个更简单的案例
为简单起见,让我们从计算形式的乘积开始mult(A,A)
,mult(mult(A,A),A)
以此类推。我们也可以将A强加为一个简单的矩阵,这意味着它的每个元素都是一维字符串,而不是字符串的串联。
让我们举个例子。让我们将A定义为 3 维矩阵 A <- matrix(c("a","b",0,0,"c","d",0,0,"e"),3,3)
,那么A乘以A应该是 mult(A,A) = matrix(c("aa",c("ab","bc"),"bd",0,"cc",c("cd","de"),0,0,"ee"),3,3)
并且A 3应该是 mult(mult(A,A),A) = matrix(c("aaa",c("aab","abc","bcc"),c("abd","bcd","bde"),0,"ccc",c("ccd","cde","dee"),0,0,"eee"),3,3)
。
问题
你将如何实现这一点?哪种语言看起来更合适?