我希望尝试在Haskell中重写我的数据透视例程,但我立刻遇到了困难...
这是我原来的Python例程(我已经添加了大量注释以弥补类型缺失):
def pivot(entering, leaving, B, A, Z):
"""
@param entering integer indicating the entering col #
@param leaving integer indicating the leaving col #
@param B vector/array of integers, representing the basis
@param A matrix of floating point numbers
@param Z vector/array of floating point numbers
returns tuple:
(B, A, Z) with pivoted tableau
"""
# Copy A
M = [row for row in A]
# Append Z row to the matrix
M.append(Z)
# Find the main row
eq_no = B.index(leaving)
col = entering
# Go through all other rows and do Gaussian elimination on them:
for i in range(len(M)):
if i == eq_no:
continue
# Do pivot - ignore "zero_out" function for now
# assume it returns a vector same size as row M[i]
M[i] = zero_out(M[i], M[eq_no], col)
# Reassign B's
Bprime = [b for b in B] # copy B
Bprime[eq_no] = entering # replace
# return new B, matrix M (less 1 row), and last row of M
return (Bprime, M[:len(M)-1], M[len(M)-1])
这是我目前的进展...
type Matrix = [ [Double] ]
type Vector = [ [Vector] ]
matrix = [ [1, 2, 3], [2, 3, 4]]
hello:: Matrix -> Int
hello m = length m
pivot:: Int -> Int -> Vector -> Matrix -> Matrix -> Matrix
pivot entering leaving b a z =
let m = a::z
eq_no = elemIndex leaving b
case eq_no of
Just no -> no
Nothing -> 1
col = entering
in ????
我非常关注人们如何实现"矩阵"和"向量"类型,以及如何操作数组-比如替换其中的元素或矩阵中的行。
如果有不清楚的地方,请告诉我,谢谢!
Vector
类型是正确的吗? - phimuemue[ foo | x <- gen, baz]
,元组语法(foo, bar)
,数组索引arr ! index
,守卫语法| predicate = expression
。这些都是相当基本的 Haskell;也许可以先阅读教程的前几节,或者从 LYAH 开始。 - Dan Burton