[erlang-questions] Erlang again!
Masklinn
masklinn@REDACTED
Thu Jul 22 17:33:20 CEST 2010
On 2010-07-22, at 13:28 , Jilani Khaldi wrote:
> Hi All,
> after a long time, here I am programming in Erlang again...
> I have 2 lists:
> L1=[1,2,3,4,5], L2=[1.1,2.2,3.3,4.4,5.5]
> and I want to have a third list which is the difference of them:
> L3=[
> L2[1] - L1[1],
> L2[2] - L1[2],
> L2[3] - L1[3],
> L2[4] - L1[4],
> L2[5] - L1[5]
> ]
> The result should be
> L3=[0.1,0.2,0.3,0.4,0.5]
>
> I have tried:
>
> sub(L2,L1) -> [X2-X1||X1<-L1,X2<-L2].
>
> but the result is so different from what I have excpected (the error due to floats calculation is not important).
>
> [0.10000000000000009,1.2000000000000002,2.3,
> 3.4000000000000004,4.5,-0.8999999999999999,
> 0.20000000000000018,1.2999999999999998,2.4000000000000004,
> 3.5,-1.9,-0.7999999999999998,0.2999999999999998,
> 1.4000000000000004,2.5,-2.9,-1.7999999999999998,
> -0.7000000000000002,0.40000000000000036,1.5,-3.9,-2.8,
> -1.7000000000000002,-0.5999999999999996,0.5]
>
> Any hint?
> Thanks!
listcomps don't iterate on both lists simultaneously, they perform a nested iteration. So for each X1 of L1 they iterate over all of L2.
What you want here is zip/2[0] or, even better, zipWith/3[1]. If the description isn't sufficient, you might be interested in the types of the equivalent function in Haskell[2].
In any case, your operation would be along the lines of:
sub(L2, L1) -> zipWith(fun(X2, X1) -> X2-X1 end, L2, L1).
[0] http://www.erlang.org/doc/man/lists.html#zip-2
[1] http://www.erlang.org/doc/man/lists.html#zipwith-3
[2] http://haskell.org/ghc/docs/6.12.1/html/libraries/base-4.2.0.0/Prelude.html#v:zipWith
More information about the erlang-questions
mailing list