Hacker News new | ask | show | jobs
by dracodoc 1911 days ago
There really should be a better way to map values. There are numerous functions in R for this, I believe there should be similar functions in Julia. Is that because Julia have good performance so people tend to write loop to deal with this kind of task? And call this hacking?

I tried paste the code but it was hard to read. You can search Histograms in this page https://datasciencejuliahackers.com/03_probability_intro.jl....

7 comments

For most cases, Julia’s broadcast syntax [1] is the easiest way to map a function over some values. When you want to do something more complex, Julia provides an incredibly flexible and powerful iterator in CartesianIndices [2].

Did you have a more specific question about mapping or iteration in Julia?

[1] https://julia.guide/broadcasting

[2] https://julialang.org/blog/2016/02/iteration/

Using a loop and `if` statements as the book does is unidiomatic, the `replace` function (and the in-place equivalent `replace!`) work as you’d expect. https://docs.julialang.org/en/v1/base/collections/#Base.repl...

If you have a mapping dict defined I think the syntax is just `replace!.(rainData.month, monthMap...)`, not tested though.

What do you mean, "map values"? There is

    [sin(x) for x in vec]
    map(sin, vec)
    sin.(vec)
which are roughly equivalent? Is that what you're referring to?
Don't forget the "lazy" version: (sin(x) for x in vec)
If you're referring to the `for` loop replacing Spanish month names with English ones, that could have been done like this [1]:

    rainData.month = map(mth -> myEsEnDict[mth], rainData.month)
[1] https://syl1.gitbook.io/julia-language-a-concise-tutorial/us...
Can you give a code example in R of what you would like to do in Julia?

There are quite a lot of different ways of mapping in Julia, including functions like `map`, `mapreduce`, `replace`, and various syntaxes for broadcasting and array comprehensions.

For maximum SIMD performance there are also things like `vmap` and `vmapreduce` from LoopVectorization.jl.

I see what you're saying, regarding the histogram code. A cleaner approach would have been to store the translations in a named tuple or Dict and iterated through it.

One of the other commenters also mentioned the `replace` function, which could be used in place of a loop.