Genesis
Genesis

Reputation: 159

Haskell Array Subtraction

I'm trying to brush up on my Linear Algebra skills and am also learning Haskell and thought...why not learn by doing one on the other! (Two birds one stone)

-- Vector

a = [1,0,0]
b = [2,0,4]

subTwoLists (x:xs) (y:ys) = (x-y) : (subTwoLists xs ys)

What I'd really like to understand:

Upvotes: 1

Views: 1667

Answers (1)

Sibi
Sibi

Reputation: 48654

There is a problem with this code:

subTwoLists :: Num a => [a] -> [a] -> [a]
subTwoLists (x:xs) (y:ys) = (x-y) : (subTwoLists xs ys)

You are not handling the base case. In recursion, you always have to handle the base case. Something like this should work:

subTwoLists :: Num a => [a] -> [a] -> [a]
subTwoLists [] _ = []
subTwoLists _ [] = []
subTwoLists (x:xs) (y:ys) = (x-y) : (subTwoLists xs ys)

Do these just mean for all elements in a and all elements in b?

Yes. But Why don't you try it yourself in ghci?

(x-y) : Should compute a[0] - b[0] = c[0] right?

Yes.

Also, note that you are using Lists, not arrays.

Upvotes: 4

Related Questions