Reputation: 159
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:
(x:xs)
and (y:ys)
: Do these just mean for all elements in a and all elements in b?
= (x-y)
: Should compute a[0] - b[0] = c[0]
, right?
Upvotes: 1
Views: 1667
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