10 Julia Recipes You Can't Miss

This trick is absolutely brilliant. Is the semicolon before x = rand() necessary. I could run the code without it.

2 Likes

Thank you. I think you are right, it seems like the ; is not necessary, it works without it for me as well even on old versions of Julia.

1 Like

(x = something, y = something_else) for constructing NamedTuples has been around since 1.0. The novelties since then were (; x, y) for constructing a NamedTuple from variables in scope (instead of having to write (x=x, y=y)) in 1.5, and then applying that to destructuring, i.e. (; x, y) = something where something is an object that has fieldnames x and y in Julia 1.7.

8 Likes
julia> abc = (a=1, b="hello", c = 3.14)
(a = 1, b = "hello", c = 3.14)
julia> ac = NamedTuple{(:a, :c)}(abc)
(a = 1, c = 3.14)
"""
    keepkeys(nt::NamedTuple, syms::Tuple{Vararg{Symbol}})

Construct a subset of `nt` using only the keys in `syms`.
""" keepkeys

julia> keepkeys(nt::NamedTuple, ks=NTuple{N,Symbol} where {N}) =
                 NamedTuple{ks}(nt)

julia> b = keepkeys(abc, (:b,))
(b = "hello",)

julia> bc = keepkeys(abc, (:b, :c))
(b = "hello", c = 3.14)

julia> keepkeys(abc, (:z,))
ERROR: type NamedTuple has no field z
"""
    omitkeys(nt::NamedTuple, syms::Tuple{Vararg{Symbol}})

Construct a subset of `nt` omitting the keys in `syms`.
""" omitkeys

julia>  omitkeys(nt::NamedTuple, ks=NTuple{N,Symbol} where {N}) =
                  keepkeys(nt, Tuple(setdiff(keys(nt), ks)))

julia> bc = omitkeys(abc, (:a,))
(b = "hello", c = 3.14)

julia> b = omitkeys(abc, (:a, :c))
(b = "hello",)

julia> abc2 = omitkeys(abc, (:z,))
(a = 1, b = "hello", c = 3.14)
3 Likes

hypot(p.x, p.y) is nicer

3 Likes

Only if you are familiar with that function; otherwise the formula is unambiguous and hence preferable.

3 Likes

When I have to use a for-loop to get an output, I find really useful to initialize the vector as a keyword argument.
Example:

function foo(x)
    output = similar(x)
    
    for i in eachindex(x)
        output[i] = x[i] + 1
    end

    return output
end

instead, I use

function foo(x; output = similar(x))    
    for i in eachindex(x)
        output[i] = x[i] + 1
    end

    return output
end

This is possible because you can use previous arguments to define default values of a keyword argument.

6 Likes

I like that because the output appears in the function statement: a very handy heads-up for the user.

-100. It is worth it to fire up the Julia REPL just to use this nice function and avoid the pain of writing the square root of the sum of the squares.

+100=0. Sorry, I need a bit of context…

1 Like

quick note: An undefined name inside omitkeys is now repaired.
q.v. two recipes for subselecting entries in a NamedTuple.

The second solution seems to be more efficient. Isn’t it.

 @time b = foo(1:100) #first one
  0.000023 seconds (1 allocation: 896 bytes)
 @time b = foo(1:100) #second one
  0.000008 seconds (1 allocation: 896 bytes)

There should be no difference, or at most a negligible difference.

Recall that to compute times, either use @time and execute the function at least twice (the first run is always polluted by compilation time). But to do serious benchmarks, use the package BenchmarkTools and @btime. This computes multiple times the calculation to provide a more accurate benchmark.

2 Likes

Something I find extremely useful for reading files: eachline I/O and Network · The Julia Language

Also note that reverse needs to be qualified as Iterators.reverse in recent Julia versions.

Edit: Note however that reverse will not work with eachline, unlike Iterators.reverse.

1 Like

Updated in the article.

For h. - see also Why are there all these strange stumbling blocks in Julia? - #67 by Eben60

e.g.

function retMultipleValues()
    v1,v2 = "India","Iran"
    return (; v1,v2)
end

Also, you might want to link this thread: Seven Lines of Julia (examples sought)

1 Like

That doesn’t sound right. You might mean that Iterators.reverse knows how to reverse eachline iterators in recent Julia versions. reverse from Base has never known how to do that.

2 Likes

Yes, that’s right, my bad

1 Like

Now updated to include around 21 recipes. Please give feedback on items 11-21.