[英]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.