[Haskell-beginners] Weird (++) behavior when adding 2 vectors
Lorenzo Bolla
lbolla at gmail.com
Tue Oct 18 14:48:40 CEST 2011
Hi,
On Tue, Oct 18, 2011 at 1:19 PM, Alexander Raasch <info at alexraasch.de>wrote:
> Hi,
>
> so I wrote this function to add two vectors represented as lists:
>
> add a b = add' a b [] where
> add' [] [] s = s
> add' (a:as) (b:bs) s ++ [a+b]
>
>
I think something mangled your function, as this is not valid Haskell code.
Anyway, I tried to rewrite your function.
The first version works as expected; the second gives reversed output.
Note that there is no need for the accumulator "s".
add a b = add' a b
where add' [] [] = []
add' (a:as) (b:bs) = [a+b] ++ (add' as bs)
add a b = add' a b
where add' [] [] = []
add' (a:as) (b:bs) = (add' as bs) ++ [a+b] -- reversed output
Obviously, the same function can be written as:
zipWith (+) [1,2,3] [1,2,3]
hth,
L.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20111018/159bbe5b/attachment.htm>
More information about the Beginners
mailing list