# Fun One Liners

**URL:** <https://discourse.julialang.org/t/fun-one-liners/28352>\
**Category:** General Usage\
**Created:** [September 3, 2019, 11:13pm UTC](https://discourse.julialang.org/t/fun-one-liners/28352 "2019-09-03T23:13:18Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![anon92994695](https://avatars.discourse-cdn.com/v4/letter/a/ce7236/32.png) [@anon92994695](https://discourse.julialang.org/u/anon92994695)\
**Post date:** [September 3, 2019, 11:13pm UTC](https://discourse.julialang.org/t/fun-one-liners/28352/1 "2019-09-03T23:13:18Z")

</div>

Would it be fun to have a thread where people share really fancy one liners? I think so - I think it’d be a great way to show off some of Julia to newcomers but also share some cool code. I’ll kick the thread off with 2-3,

```julia
"""
    SquareEuclideanDistance(X)
Returns the squared Grahm aka the euclidean distance matrix of `X`.
Note: Tamas Paap correctly showed this should be two lines for performance. 
"""
SquareEuclideanDistance(X) = ( sum(X .^ 2, dims = 2) .+ sum(X .^ 2, dims = 2)') .- (2 * X * X')

```

Source: [https://github.com/caseykneale/ChemometricsTools.jl/blob/master/src/DistanceMeasures.jl](https://github.com/caseykneale/ChemometricsTools.jl/blob/master/src/DistanceMeasures.jl)

```julia
"""
    SquareEuclideanDistance(X, Y)
Returns the squared euclidean distance matrix of X and Y such that the columns are the samples in Y.
"""
SquareEuclideanDistance(X, Y) = ( sum(X .^ 2, dims = 2) .+ sum(Y .^ 2, dims = 2)') .- (2 * X * Y')

```

Source: [https://github.com/caseykneale/ChemometricsTools.jl/blob/master/src/DistanceMeasures.jl](https://github.com/caseykneale/ChemometricsTools.jl/blob/master/src/DistanceMeasures.jl)

```julia
"""
Sinc interpolation
Y - vector of a line shape
S - Sampled domain of Y
Up - Upsampled X vector
"""
SincInterpolation(Y, S, Up) = sinc.( (Up .- S') ./ (S[2] - S[1]) ) * Y

```

Refactored From: [https://gist.github.com/endolith/1297227#file-sinc\_interp-m](https://gist.github.com/endolith/1297227#file-sinc_interp-m)  
Note: Please include sources for where they came from if they aren’t you’re own effort!

---

<div class="post-metadata">

**Author:** ![jling](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jling/32/212909_2.png) [@jling](https://discourse.julialang.org/u/jling)\
**Post date:** [September 4, 2019, 12:03am UTC](https://discourse.julialang.org/t/fun-one-liners/28352/2 "2019-09-04T00:03:09Z")

</div>

slightly ot, but reminds me of this: [Showcase of Languages - Code Golf Stack Exchange](https://codegolf.stackexchange.com/questions/44680/showcase-of-languages)

---

<div class="post-metadata">

**Author:** ![c42f](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/c42f/32/52842_2.png) [@c42f](https://discourse.julialang.org/u/c42f)\
**Post date:** [September 4, 2019, 12:13am UTC](https://discourse.julialang.org/t/fun-one-liners/28352/3 "2019-09-04T00:13:05Z")

</div>

Cool idea. Here’s a fun one from my REPL session a couple of days ago:

```julia
using CSV, Glob

# Read and concatenate all tables in CSV files matching the given `pattern`
cat_csv(pattern) = vcat(CSV.read.(glob(pattern))...)

```

Broadcast is great for so many things which aren’t numbers.

---

<div class="post-metadata">

**Author:** ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)\
**Post date:** [September 4, 2019, 7:31am UTC](https://discourse.julialang.org/t/fun-one-liners/28352/4 "2019-09-04T07:31:56Z")

</div>

> [@anon92994695](#):
>
> `( sum(X .^ 2, dims = 2) .+ sum(X .^ 2, dims = 2)') .- (2 * X * X')`

This is a nice example about the _dangers_ of preferring one-liners: you seem to be calculating `sum(X .^ 2, dims = 2)` _twice_. You can rewrite this exact same algorithm as

```julia
X2 = sum(X .^ 2, dims = 2)
(X2 .+ X2') .- (2 * X * X')

```

but then of course it is not a one-liner anymore 😉

That said, I would just do something like

```julia
abs2.(X .- X')

```

which should have better numerical properties.

I don’t think one should ever purposefully write one-liners in Julia. If a function turns out to fit on one line, fine, if it doesn’t, then it doesn’t. Trying to make it “fancy” just leads to obfuscated and occasionally suboptimal code.

For example, in

```julia
function calculate_foo_bar(X, Y)
    foo = some_complicated_expression
    bar = some_other_complicated_expression
    foo, bar
end

```

is much more readable and easier to refactor than

```julia
function calculate_foo_bar(X, Y)
    some_complicated_expression, some_other_complicated_expression
end

```

Since there is no cost to just naming partial results in variables and using them that way, it is generally preferable when it makes code easier to read.

---

<div class="post-metadata">

**Author:** ![anon92994695](https://avatars.discourse-cdn.com/v4/letter/a/ce7236/32.png) [@anon92994695](https://discourse.julialang.org/u/anon92994695)\
**Post date:** [September 4, 2019, 11:23am UTC](https://discourse.julialang.org/t/fun-one-liners/28352/5 "2019-09-04T11:23:24Z")

</div>

Awe man, there goes my fun with a lecture… It’s a little bit of a hyperbole to say it’s ‘dangerous’, but yea I didn’t clean up that first function. You’re right it is more efficient to express that first function as you have but the one-line the solution you offer only works for vectors and fails on matrices.

```julia
SquareEuclideanDistance(X) = ( sum(X .^ 2, dims = 2) .+ sum(X .^ 2, dims = 2)') .- (2 * X * X')
tp(X) = abs2.(X .- X')

A = [[1 2 3 4 5]; [6 7 8 9 10]]
SquareEuclideanDistance(A)
tp(A)#cannot broadcast the array...

```

If you look at the second function I posted. What you see is that the first function is a nongeneral use-case of that.

I timed the second function and it was as optimal as I could get that operation to be due to broad-casting and outperformed many variants written in python and works easily on GPUArrays. My mistake was not taking the time to work through it for the case where X == Y. Readability is important but efficiency/performance really matters when calculating distance matrices. My apologies.

---

<div class="post-metadata">

**Author:** ![mthelm85](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mthelm85/32/224164_2.png) [@mthelm85](https://discourse.julialang.org/u/mthelm85)\
**Post date:** [September 4, 2019, 11:48am UTC](https://discourse.julialang.org/t/fun-one-liners/28352/6 "2019-09-04T11:48:14Z")

</div>

So my example isn’t as nifty as yours, but my single favorite feature of Julia is the array comprehension:

```julia
my_vector = [2^i for i in 1:10]

```

Add to this the ability to toss in a conditional statement and a broadcasting operation and I’m a very happy coder 😉:

```julia
my_vector = [2^i ./ 2 for i in 1:10 if iseven(i)] 

```

---

<div class="post-metadata">

**Author:** ![anon92994695](https://avatars.discourse-cdn.com/v4/letter/a/ce7236/32.png) [@anon92994695](https://discourse.julialang.org/u/anon92994695)\
**Post date:** [September 4, 2019, 11:52am UTC](https://discourse.julialang.org/t/fun-one-liners/28352/7 "2019-09-04T11:52:27Z")

</div>

> [@mthelm85](#):
>
> my\_vector = [2^i ./ 2 for i in 1:10 if iseven(i)]

There’s no rules on complexity, just fun one liners!  
For fun here’s an alternative to yours that keeps things as integer types:

```julia-auto
my_vector = [2^(i-1) for i in 2:2:10]

```

---

<div class="post-metadata">

**Author:** ![mthelm85](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mthelm85/32/224164_2.png) [@mthelm85](https://discourse.julialang.org/u/mthelm85)\
**Post date:** [September 4, 2019, 11:55am UTC](https://discourse.julialang.org/t/fun-one-liners/28352/8 "2019-09-04T11:55:58Z")

</div>

> For fun here’s an alternative to yours that keeps things as integer types

Hmmm, I see…so my example wasn’t type stable because `1:10` are integers, but the `./ 2` operation causes them to be converted to floats, right? I’ve seen that people sometimes go to great lengths to achieve type stability but I’m not sure what the issue is. Is it just a performance concern? (sorry to change the topic of the thread)

Would this solve the type instability issue with my above example?

```julia
[2.0^i ./ 2.0 for i in 1.0:10.0 if iseven(i)]

```

---

<div class="post-metadata">

**Author:** ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)\
**Post date:** [September 4, 2019, 12:04pm UTC](https://discourse.julialang.org/t/fun-one-liners/28352/9 "2019-09-04T12:04:59Z")

</div>

> [@mthelm85](#):
>
> so my example wasn’t type stable

[Type stability](https://docs.julialang.org/en/v1/manual/faq/#man-type-stability-1) is a concept that is only applicable to functions, and your code isn’t one — it’s calculating a constant. BTW, the compiler can infer it perfectly fine:

```julia
julia> my_vector(n) = [2^i ./ 2 for i in 1:n if iseven(i)]
my_vector (generic function with 1 method)

julia> @code_warntype my_vector(10)
Variables
  #self#::Core.Compiler.Const(my_vector, false)
  n::Int64
  #17::var"##17#18"

Body::Array{Float64,1}
1 ─ (#17 = %new(Main.:(var"##17#18")))
│ %2 = #17::Core.Compiler.Const(var"##17#18"(), false)
│ %3 = (1:n)::Core.Compiler.PartialStruct(UnitRange{Int64}, Any[Core.Compiler.Const(1, false), Int64])
│ %4 = Base.Filter(Main.iseven, %3)::Core.Compiler.PartialStruct(Base.Iterators.Filter{typeof(iseven),UnitRange{Int64}}, Any[Core.Compiler.Const(iseven, false), Core.Compiler.PartialStruct(UnitRange{Int64}, Any[Core.Compiler.Const(1, false), Int64])])
│ %5 = Base.Generator(%2, %4)::Core.Compiler.PartialStruct(Base.Generator{Base.Iterators.Filter{typeof(iseven),UnitRange{Int64}},var"##17#18"}, Any[Core.Compiler.Const(var"##17#18"(), false), Core.Compiler.PartialStruct(Base.Iterators.Filter{typeof(iseven),UnitRange{Int64}}, Any[Core.Compiler.Const(iseven, false), Core.Compiler.PartialStruct(UnitRange{Int64}, Any[Core.Compiler.Const(1, false), Int64])])])
│ %6 = Base.collect(%5)::Array{Float64,1}
└── return %6

```

Whether one prefers integers or floats in the result depends on the context, implicit type conversions can work just fine.

---

<div class="post-metadata">

**Author:** ![MrUrq](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mrurq/32/8924_2.png) [@MrUrq](https://discourse.julialang.org/u/MrUrq)\
**Post date:** [September 4, 2019, 1:38pm UTC](https://discourse.julialang.org/t/fun-one-liners/28352/10 "2019-09-04T13:38:15Z")

</div>

If you want to keep it as ints using your solution you could use `÷ (\div)`

```julia
[2^i ÷ 2 for i in 1:10 if iseven(i)]

```

although @anon92994695 solution is slightly faster

---

<div class="post-metadata">

**Author:** ![DNF](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dnf/32/10191_2.png) [@DNF](https://discourse.julialang.org/u/DNF)\
**Post date:** [September 4, 2019, 1:49pm UTC](https://discourse.julialang.org/t/fun-one-liners/28352/11 "2019-09-04T13:49:22Z")

</div>

> [@mthelm85](#):
>
> Hmmm, I see…so my example wasn’t type stable because `1:10` are integers, but the `./ 2` operation causes them to be converted to floats, right?

Actually, it’s the `/ 2` that yields floats, the broadcasting dot does nothing here, since it’s pure scalar division.

> [@mthelm85](#):
>
> Would this solve the type instability issue with my above example?
> 
> ```julia-auto
> [2.0^i ./ 2.0 for i in 1.0:10.0 if iseven(i)]
> 
> ```

There is no type stability issue, integer divided by integer gives a float, and that is perfectly predictable. The new code is float divided by float, which, predictably, gives a float.

Type instability means that the compiler is unable to predict the types in your code, because they can change based on the _value_ of your inputs (as opposed to their _types_). So both of your expressions were type stable.

**Edit:** BTW, `iseven` only works for `Integer`s not floats.

---

<div class="post-metadata">

**Author:** ![MrUrq](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mrurq/32/8924_2.png) [@MrUrq](https://discourse.julialang.org/u/MrUrq)\
**Post date:** [September 4, 2019, 2:23pm UTC](https://discourse.julialang.org/t/fun-one-liners/28352/12 "2019-09-04T14:23:32Z")

</div>

@stevengj posted a nice one liner in [How to use minimum and maximum for a Vector{SVector{3}}](https://discourse.julialang.org/t/how-to-use-minimum-and-maximum-for-a-vector-svector-3/26235). The idea is to find the smallest component of the first, second, third … element in a vector of vectors.

```julia
A = [rand(3) for i = 1:10]
reduce((x,y) -> min.(x,y), A)

```

It is fast and works for other types to

```julia
A = [Tuple(rand(3)) for i = 1:10]
reduce((x,y) -> min.(x,y), A)

```

```julia
using StaticArrays
A = [SVector{3}(rand(3)) for i = 1:10]
reduce((x,y) -> min.(x,y), A)

```

---

<div class="post-metadata">

**Author:** ![ChrisRackauckas](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/chrisrackauckas/32/77_2.png) [@ChrisRackauckas](https://discourse.julialang.org/u/ChrisRackauckas)\
**Post date:** [September 4, 2019, 3:16pm UTC](https://discourse.julialang.org/t/fun-one-liners/28352/13 "2019-09-04T15:16:44Z")

</div>

```julia
while true; end

```

---

<div class="post-metadata">

**Author:** ![anon92994695](https://avatars.discourse-cdn.com/v4/letter/a/ce7236/32.png) [@anon92994695](https://discourse.julialang.org/u/anon92994695)\
**Post date:** [September 4, 2019, 7:27pm UTC](https://discourse.julialang.org/t/fun-one-liners/28352/14 "2019-09-04T19:27:37Z")

</div>

😆

Here’s one for you Chris,

```julia
f(x) = f(x); f(Inf)

```

---

<div class="post-metadata">

**Author:** ![MatFi](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/matfi/32/10002_2.png) [@MatFi](https://discourse.julialang.org/u/MatFi)\
**Post date:** [September 4, 2019, 9:28pm UTC](https://discourse.julialang.org/t/fun-one-liners/28352/15 "2019-09-04T21:28:00Z")

</div>

here we go (actually not a julia and only linux):

```julia
run(pipeline(pipeline(pipeline(pipeline(`cat /dev/urandom`,`hexdump -v -e '/1 "%u\n"'`),`awk '{ split("0,1,2,4,8",a,",");for (i = 0; i < 1; i+= 0.0001) printf("%08X\n", 100*sin(1382*exp((a[$1 % 8]/12)*log(2))*i)) }'`),`xxd -r -p`),`aplay -c 2 -f S32_LE -r 30000`))

```

---

<div class="post-metadata">

**Author:** ![anon92994695](https://avatars.discourse-cdn.com/v4/letter/a/ce7236/32.png) [@anon92994695](https://discourse.julialang.org/u/anon92994695)\
**Post date:** [September 6, 2019, 1:50am UTC](https://discourse.julialang.org/t/fun-one-liners/28352/16 "2019-09-06T01:50:22Z")

</div>

here’s one of my favorites… Just came into use in my new package 😃

```julia
#Approximate the derivative of an arbitrary edit - complex analytic function(fn) at a given point x.
ComplexStepDerivative(fn, x, eps = 1e-11) = imag( fn( x + (eps * 1.0im)) ) / eps

```

Example usage:

```julia
using Plots
Plots.plot( ComplexStepDerivative.(cos, 0:(pi/100):2*pi), label = "Complex Step Derivative" );
Plots.plot!( -sin.( 0:(pi/100):2*pi ), label = "Analytic Derivative", legend = :bottomright )

```

---

<div class="post-metadata">

**Author:** ![c42f](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/c42f/32/52842_2.png) [@c42f](https://discourse.julialang.org/u/c42f)\
**Post date:** [September 6, 2019, 2:55am UTC](https://discourse.julialang.org/t/fun-one-liners/28352/17 "2019-09-06T02:55:41Z")

</div>

That _is_ a neat trick, though `ForwardDiff.derivative` would be better — it’s almost the same trick numerically but using dual numbers rather than complex numbers for the automatic differentiation. This is more principled and has many tricks to make it more robust:

```julia
ForwardDiff.derivative.(cos, 0:(pi/100):2*pi)

```

---

<div class="post-metadata">

**Author:** ![xiaodai](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/xiaodai/32/15937_2.png) [@xiaodai](https://discourse.julialang.org/u/xiaodai)\
**Post date:** [September 6, 2019, 4:31am UTC](https://discourse.julialang.org/t/fun-one-liners/28352/18 "2019-09-06T04:31:20Z")

</div>

To extract the type in a `Union`

```julia
extt(::Type{Union{Missing, T}}) where T = T

```

---

<div class="post-metadata">

**Author:** ![longemen3000](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/longemen3000/32/7298_2.png) [@longemen3000](https://discourse.julialang.org/u/longemen3000)\
**Post date:** [September 6, 2019, 5:34am UTC](https://discourse.julialang.org/t/fun-one-liners/28352/19 "2019-09-06T05:34:25Z")

</div>

> [@c42f](#):
>
> That _is_ a neat trick, though `ForwardDiff.derivative` would be better — it’s almost the same trick numerically but using dual numbers rather than complex numbers for the automatic differentiation. This is more principled and has many tricks to make it more robust:

there is not ForwardDiff in Octave, and that works in Octave hahaha

---

<div class="post-metadata">

**Author:** ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)\
**Post date:** [September 6, 2019, 5:55am UTC](https://discourse.julialang.org/t/fun-one-liners/28352/20 "2019-09-06T05:55:47Z")

</div>

There was a discussion about the complex step method a while ago here:

> [@Complex step differentiation method explained](https://discourse.julialang.org/t/complex-step-differentiation-method-explained/14647):
>
> I wrote a brief post explaining the “complex step method” that was the first topic in Nick Higham’s JuliaCon 2018 talk. (Using Julia for demonstrations, of course !)

It _is_ a neat trick, but it only works for complex analytic functions, which essentially rules out all nontrivial _programs_. Moreover, it can just fail silently (without erroring), which is a debugging nightmare.

So I don’t think it is something one would use in practice in any language. Incidentally, if a language for scientific computing doesn’t allow a disciplined AD implementation in 2019, prospects for that language are quite grim.

[Next page](https://discourse.julialang.org/t/fun-one-liners/28352.md?page=2)
