[英]f: Z -> Z_n in R and haskell
是否有直接的方法将以下R代码转换为haskell?
对于任何函数f:Z - > Z_n(Z表示整数集,Z_n表示集合{0,1,2,...,(n-1)},f(i)= j当且仅当f (i)与j mod n一致,即当除以n时,f(i)与j具有相同的余数。
下面的R代码试图产生n×n矩阵M,因此当f(i)= j时,M(i,j)= 1,否则M(i,j)= 0。
# visualize functions in Z_n
zn_func = function(n, f) {
n1 = n - 1
# make a single column matrix with elements {f(0), f(1), f(2), ... f(n-1)}
x = matrix(f(0:n1), ncol = 1)
# repeat this column n times
x = x[, rep(1, n)]
# set row and col names
rownames(x) = colnames(x) = 0:n1
# get f(x) mod n
y = x %% n
# make a single row matrix with elements {0, 1, 2, 3, ..., n-1}
rs = matrix(0:n1, nrow = 1)
# repeat that row n times
rs = rs[rep(1, n), ]
rownames(rs) = colnames(rs) = 0:n1
# determine if y[i, j] == rs[i, j]
# z is a matrix of type bool
z = y == rs
# z + 0 converts z into a matrix of type integer
# FALSE -> 0, TRUE -> 1
z=z+0
list(x=x, y=y, z=z)
}
f = function(x) x^2
zn_func(7, f)
看到它的实际效果:
> zn_func(7, f)
$x
0 1 2 3 4 5 6
0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1
2 4 4 4 4 4 4 4
3 9 9 9 9 9 9 9
4 16 16 16 16 16 16 16
5 25 25 25 25 25 25 25
6 36 36 36 36 36 36 36
$y
0 1 2 3 4 5 6
0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1
2 4 4 4 4 4 4 4
3 2 2 2 2 2 2 2
4 2 2 2 2 2 2 2
5 4 4 4 4 4 4 4
6 1 1 1 1 1 1 1
$z
0 1 2 3 4 5 6
0 1 0 0 0 0 0 0
1 0 1 0 0 0 0 0
2 0 0 0 0 1 0 0
3 0 0 1 0 0 0 0
4 0 0 1 0 0 0 0
5 0 0 0 0 1 0 0
6 0 1 0 0 0 0 0
$z
部分就是我们追求的目标。 在这种情况下,它表示在Z_7中,在f(x)= x ^ 2下,f(6)= 1,f(4)= f(3)= 2,f(2)= 4等。
我已经尝试过hmatrix库,但它甚至不允许使用整数矩阵。 它可以使用列表列表,但我更喜欢使用现有的库来为矩阵操作做好准备。
以下是我对#haskell irc频道进行一些讨论后所做的事情:
import Numeric.LinearAlgebra
znFunc n f = res where
res_raw = [[if f i `rem` n == j then 1 else 0 | j <- [0 .. (n-1)]] | i <- [0 .. (n-1)]]
res = fromRows $ map fromList res_raw
测试:
> znFunc 7 (^2)
(7><7)
[ 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0
, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0
, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0
, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0
, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0
, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0
, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0 ]
结果与R中的结果相同。打印不如R中那么漂亮,但此时我不知道如何改进它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.