On Monday, February 10, 2014 4:50:41 PM UTC-5, N. Saphra wrote:
>
> The following code doesn't behave as I'd expect:
>
> julia> reduce((x,y) -> (x * int(y)), 1, ["1", "2", "3"])
> ERROR: no method *(ASCIIString,Int64)
>  in anonymous at none:1
>  in r_pairwise at reduce.jl:135
>  in reduce at reduce.jl:183
>
> I was expecting reduce() to take my op and do something like *(*(*(1, 
> int("1")), int("2")), int("3")) (I understand the associativity is not 
> guaranteed, but * is associative anyway). Instead it gives this error. Am I 
> misunderstanding something?
>

It's not working because the correctness of your code depends on 
associativity.  For example, if it associates from right to left, then the 
first call to your function will pass ("2","3"), for which "2" * int("3") 
fails.

You are assuming a left-associative sum, which is not in fact what reduce 
uses.    As Ivar said, in 0.3 there will be a foldl function that does 
this.    Or you can use:

    reduce((x,y) -> (int(x) * int(y)), 1, ["1", "2", "3"])

Or as Ivar said you can just use a loop, which will be faster anyway (and 
probably clearer, if not shorter):

     result = 1; for s in ["1", "2", "3"] result *= int(s); end; result

 

Reply via email to