Broadcasting and pairs using `.=>`

In replace a pair is used to specify a pattern and its replacement, as in replace("123", "2" => "two"). When broadcasting, the following won’t work (as expected) as a pair is iterable: replace.(["123", "246"], "2"=>"two"). The solution is to wrap the pair into a length-1 container or use Ref, as with replace.(["123", "246"], Ref("2"=>"two")). Okay, but this syntax also works: replace.(["123", "246"], "2" .=> "two"). My question, is this by design and expected behaviour or may it be changed in the future? I personally like it, though can’t explain to myself why exactly it works.

Yes, this is by design — what’s happening is that strings broadcast like scalars. And broadcasting over two scalars is completely supported. The only thing you need to consider is that broadcasted operators end up “on the inside” of the fused for loop, and will repeatedly be evaluated for each iteration. In this case, I’m quite certain it’ll essentially be a no-op, but you might have a more expensive function or a function with side-effects (like rand.() vs rand()) in which case there will be more dramatic effects.

1 Like

Sure! There’s nothing special about => ; it’s just a shorthand for Pair. So your example can also be written as:

julia> replace.(["123", "246"], Pair.("2", "two"))
2-element Array{String,1}:
 "1two3"
 "two46"

Fore more on why that works, see More Dots: Syntactic Loop Fusion in Julia

1 Like

Thanks. The thing that caught me was Pair.("2", "two") evaluates to "2" => "two" so got confused forgetting the pass happens at the syntax level, not after evaluation. Thanks for pointing to that blog post for the reminder.

1 Like