daForce93
daForce93

Reputation: 23

Value of a vector in Haskell

I'm trying to learn Haskell from Learn You a Haskell for Great Good. I'm trying to build a bunch of functions to perform various vector operations. I'm building a function that takes two vectors, and finds the angle in between them. The operation looks like this: A · B = A B cos θ

Anyway, right now I'm trying to write a function that will find "Value" of a Vector. For example, the value of 2i + 3j + 4k is sqrt(2^2 + 3^2 + 4^2).

The vector is stored as a list, and I was thinking of trying something like this:

getValue (vector) = [sqrt v | v <- v + square take 1 vector]

How would I do that?

Upvotes: 1

Views: 635

Answers (3)

Landei
Landei

Reputation: 54574

First define scalar multiplication, which is useful in its own right. I used |*| as operator:

(|*|) = (sum .) . zipWith (*)

Then the rest is trivial:

norm v = sqrt $ v |*| v

Upvotes: 2

Lee
Lee

Reputation: 144126

Assuming you are representing your vectors as a list then:

getValue :: (Floating a) => [a] -> a
getValue = sqrt . sum . map (\i -> i * i)

Alternatively you can use a list comprehension to do the squaring of values:

getValue :: (Floating a) => [a] -> a
getValue vector = sqrt . sum $ [x * x | x <- vector]

Upvotes: 1

Daniel Fischer
Daniel Fischer

Reputation: 183873

The usual name for this is "norm", or more precisely "Euclidean norm". You sum up the squares of the components and calculate the square root of the sum. With the vectors represented as lists of components, it becomes

-- assuming the component type is Double
norm :: Vector -> Double
norm vector = sqrt $ sum [x*x | x <- vector]

or, with map instead of the list comprehension,

norm vector = sqrt . sum $ map (\x -> x*x) vector

If you like point-free style, you can also write the latter as

norm :: Vector -> Double
norm = sqrt . sum . map (\x -> x*x)

Upvotes: 3

Related Questions