[Haskell-beginners] Weird (++) behavior when adding 2 vectors

Vlad Hanciuta wladsh at gmail.com
Tue Oct 18 14:36:40 CEST 2011


Hi,

Your code is not valid syntactically, I guess the last equation for add' is "add' (a:as) (b:bs) s = add' as bs s ++ [a+b]". In that case, the function application binds stronger that ++ operator so the expression is actually equivalent to "(add' as bs s) ++ [a+b]". So you can easily see that the list is computed backwards.

Vlad

On 18 Oct 2011, at 14:19, Alexander Raasch 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]
> 
> OK, I tried this in ghci:
> 
> > add [1,2,3] [1,2,3]
> [6,4,2]
> 
> Hm, I expected the result to be [2,4,6], of course, since the currently added components always go to the end of the resulting vector. I then changed the last term in add' to
> 
> [a+b] ++ s ,
> 
> but still
> 
> > add [1,2,3] [1,2,3]
> [6,4,2]
> 
> Can anyone explain this behavior to me. I think there should be some change in the result, no?
> 
> Alex
> 
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners




More information about the Beginners mailing list