2

I just started learning Haskell and am having trouble with using the hmatrix library. I want to write some simple code to compute the eigenvalue using the power iteration method. I start with:

c = fromList [4.0, 4.0, 4.0, 4.0]::Vector Double
n = norm2 c

Which creates a vector c and finds the 2-norm of the vector.

Multiplication with c:

c * 2 (Works)
c * 0.5 (Works)
c * pi (Works)
c * n (Error)

I checked that:

>:t pi
pi :: Floating a => a
>:t n
n :: Double

The problem is with the types but I do not know how to get around it.

Would I need to define my own (/) function in this case?

Update: The error I obtain from ghci:

Couldn't match expected type `Vector Double'
            with actual type `Double'
In the second argument of `(*)', namely `n'
In the expression: c * n
In an equation for `it': it = c * n
4

2 回答 2

2

通过检查类型,您正在做正确的事情。如果我们更明确一点,我们可以看到发生了什么。

Prelude Numeric.LinearAlgebra> :t let a = 2; b = c * a in a
let a = 2; b = c * a in a :: Vector Double

问题是 is 的类型,norm2 c因此Double不能变成Vector Double

2让我们看看前面那个多态的值。

Prelude Numeric.LinearAlgebra> let a = 2; b = c * a in a
fromList [2.0]

所以与其,n = fromList [norm2 c]

编辑:同一个库公开scalarscale您应该研究的功能。

于 2013-11-07T04:52:03.003 回答
2

(*)假设它的两个参数具有相同的类型:

(*) :: (Num a) => a -> a -> a

您的前三个乘法起作用的原因是因为在所有三种情况下,正确的参数都成功地被类型检查为Vector Double!

要了解原因,让我们问ghci一下这三个参数的类型是什么:

> :t 2
2 :: Num a => a
> :t 0.5
0.5 :: Fractional a => a
> :t pi
pi :: Floating a => a

所有这三个都是有效Vector Double的,因为hmatrix提供了以下三个实例:

instance Num (Vector Double) where ...

instance Fractional (Vector Double) where ...

instance Floating (Vector Double) where ...

换句话说,由于这些实例,Haskell 将自动将20.5pi转换为s。Vector Double

这解释了为什么您的最后一个示例没有类型检查。 n有 type Double,这意味着它不可能将类型检查也作为Vector Double.

于 2013-11-07T04:54:01.627 回答