[Haskell-beginners] Weird (++) behavior when adding 2 vectors
Alexander Raasch
info at alexraasch.de
Tue Oct 18 15:04:25 CEST 2011
Hi,
thanks for your answers. I'm exercising with different programming
techniques, so the use of an accumulator was intentional although not
necessary. As Vlad said, my mistake was the stronger binding of the
function application. Sigh, ...
Thank you all again.
Alex
On 10/18/2011 02:48 PM, Lorenzo Bolla wrote:
> Hi,
>
> On Tue, Oct 18, 2011 at 1:19 PM, Alexander Raasch <info at alexraasch.de
> <mailto: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/a500e224/attachment-0001.htm>
More information about the Beginners
mailing list