# 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:** 4

<div class="post-metadata">

**Author:** ![oschulz](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/oschulz/32/2998_2.png) [@oschulz](https://discourse.julialang.org/u/oschulz)\
**Post date:** [September 16, 2019, 11:02am UTC](https://discourse.julialang.org/t/fun-one-liners/28352/61 "2019-09-16T11:02:44Z")

</div>

> [@Tamas\_Papp](#):
>
> 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

Hm, If we had a way to mark a function as pure (no side effects, I don’t mean `Base.@pure`), the Julia compiler could potentially recognize such duplications and optimize them away. I assume this will have been considered already multiple times by core (and other) Julia developers - but does anybody know if there’s concrete work going in in that direction, currently?

---

<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 16, 2019, 11:09am UTC](https://discourse.julialang.org/t/fun-one-liners/28352/62 "2019-09-16T11:09:17Z")

</div>

There was

[https://github.com/rdeits/CommonSubexpressions.jl](https://github.com/rdeits/CommonSubexpressions.jl)

but I am not sure this is being considered at the language level.

IMO just assigning the common part to a variable is much cleaner anyway (in terms of code readability).

---

<div class="post-metadata">

**Author:** ![oschulz](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/oschulz/32/2998_2.png) [@oschulz](https://discourse.julialang.org/u/oschulz)\
**Post date:** [September 16, 2019, 11:13am UTC](https://discourse.julialang.org/t/fun-one-liners/28352/63 "2019-09-16T11:13:52Z")

</div>

> [@Tamas\_Papp](#):
>
> IMO just assigning the common part to a variable is much cleaner anyway (in terms of code readability).

I agree, in many cases it is, especially with more heavyweight functions.

But with more lightweight functions, e.g. used several times in a (not too long) mathematical expression, manual re-use of results can make the code less readable, as it increases the difference between the code and the “natural” representation. Of course if the functions are _very_ lightweight, inlining and `@fastmath` can sometimes do the job automatically, but in many cases they can’t.

---

<div class="post-metadata">

**Author:** ![chakravala](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/chakravala/32/6832_2.png) [@chakravala](https://discourse.julialang.org/u/chakravala)\
**Post date:** [September 16, 2019, 11:17am UTC](https://discourse.julialang.org/t/fun-one-liners/28352/64 "2019-09-16T11:17:21Z")

</div>

You can also use my pkg [Reduce.jl](https://github.com/chakravala/Reduce.jl) for that if you want symbolic optimized common sub-expressions

```Julia
julia> using Reduce; load_package(:scope)

julia> Algebra.optimize(:(z = a^2*b^2+10*a^2*m^6+a^2*m^2+2*a*b*m^4+2*b^2*m^6+b^2*m^2))
quote
    g40 = b * a
    g44 = m * m
    g41 = g44 * b * b
    g42 = g44 * a * a
    g43 = g44 * g44
    z = g41 + g42 + g40 * (2g43 + g40) + g43 * (2g41 + 10g42)
end

```

or if you really want `@pure` you can just locally define a new method for that like I described here

> [@Marking more standard library methods as pure to enable LLVM optimizations?](https://discourse.julialang.org/t/marking-more-standard-library-methods-as-pure-to-enable-llvm-optimizations/28732/8):
>
> ```julia
> module Grassmann
> @pure binomial(n::Int,k::Int) = Base.binomial(n,k)
> end
> 
> ```
> 
> This replaces the `Base.binomial` method with a local method that is pure.

---

<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 16, 2019, 11:24am UTC](https://discourse.julialang.org/t/fun-one-liners/28352/65 "2019-09-16T11:24:46Z")

</div>

I am a little stuck on this because I agree with both of you.

In machine learning and physics there are often large block matrices where certain computations are repeated. So defining a bunch of ‘extra’ variables to save on compute is a simple way to optimize. Meanwhile having it internally handled would be awesome - would lead to some expressions reading exactly how they do mathematically at no cost post compilation. However, end users may want to construct blocks with nonpure functions(unbeknownst to them) then wonder why their code is so inefficient.

---

<div class="post-metadata">

**Author:** ![oschulz](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/oschulz/32/2998_2.png) [@oschulz](https://discourse.julialang.org/u/oschulz)\
**Post date:** [September 16, 2019, 11:25am UTC](https://discourse.julialang.org/t/fun-one-liners/28352/66 "2019-09-16T11:25:25Z")

</div>

> [@chakravala](#):
>
> or if you really want `@pure` you can just locally define a new method for that like I described here

Wasn’t there some warning against `@pure` functions using non-`@pure` functions?

---

<div class="post-metadata">

**Author:** ![chakravala](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/chakravala/32/6832_2.png) [@chakravala](https://discourse.julialang.org/u/chakravala)\
**Post date:** [September 16, 2019, 11:26am UTC](https://discourse.julialang.org/t/fun-one-liners/28352/67 "2019-09-16T11:26:54Z")

</div>

> [@oschulz](#):
>
> Wasn’t there some warning against `@pure` functions using non- `@pure` functions?

No, but `@pure` is not very well documented and can cause your program to segfault, so only use it if you are extremely confident that you fully understand what you are doing with it.

Also, it is not exported from `Base` and could be pulled from under the rug at any time and change behavior.

---

<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 16, 2019, 11:27am UTC](https://discourse.julialang.org/t/fun-one-liners/28352/68 "2019-09-16T11:27:05Z")

</div>

> [@oschulz](#):
>
> But with more lightweight functions, e.g. used several times in a (not too long) mathematical expression, manual re-use of results can make the code less readable, as it increases the difference between the code and the “natural” representation.

It would be interesting to see an example.

I have the opposite view (but I recognize it is possible for rational people to disagree about these things, it is mostly a matter of taste). To make this concrete, consider the

e^{-\frac{1}{2} (X - \mu)^T \Sigma^{-1} (X - \mu)}

in the PDF of a normal distribution. For practical purposes, I would always introduce z = X - \mu and code it that way. I find code like this more maintainable.

---

<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 16, 2019, 11:29am UTC](https://discourse.julialang.org/t/fun-one-liners/28352/69 "2019-09-16T11:29:46Z")

</div>

> [@chakravala](#):
>
> if you are extremely confident that you fully understand what you are doing with it.

Cf [Bug in doc system? And question on "pure" [in docs]; meaning Julia 1.0 is close? - #5 by mbauman](https://discourse.julialang.org/t/bug-in-doc-system-and-question-on-pure-in-docs-meaning-julia-1-0-is-close/11292/5)

---

<div class="post-metadata">

**Author:** ![oschulz](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/oschulz/32/2998_2.png) [@oschulz](https://discourse.julialang.org/u/oschulz)\
**Post date:** [September 16, 2019, 12:38pm UTC](https://discourse.julialang.org/t/fun-one-liners/28352/70 "2019-09-16T12:38:46Z")

</div>

> [@Tamas\_Papp](#):
>
> To make this concrete, consider the e−12(X−μ)TΣ−1(X−μ)

That’s a good example - I would often prefer the “textbook” mathematical form in the code in such cases - having the code closer to the math helps readability, in my opinion. I don’t see why this would be more readable if broken up into several lines.

Though in this specific case, automatic elimination of common sub-expressions wouldn’t be enough - I would rewrite this completely to also avoid the creation of short-lived temporary arrays (esp. if \Sigma is smallish).

---

<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 16, 2019, 1:06pm UTC](https://discourse.julialang.org/t/fun-one-liners/28352/71 "2019-09-16T13:06:29Z")

</div>

> [@oschulz](#):
>
> I would rewrite this completely to also avoid the creation of short-lived temporary arrays (esp. if Σ\Sigma is smallish).

In practical code I would try to work with (ie store) the Cholesky decomposition \Sigma = LL^T, eg

```julia
exp(0.5 * sum(abs2, L \ (x .- mu)))

```

I think that most “textbook” formulas facilitate proof techniques, not computation (unless, of course, the textbook is on numerical methods 😉) So preserving them in code is not always a good choice. YMMV.

---

<div class="post-metadata">

**Author:** ![oschulz](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/oschulz/32/2998_2.png) [@oschulz](https://discourse.julialang.org/u/oschulz)\
**Post date:** [September 16, 2019, 1:13pm UTC](https://discourse.julialang.org/t/fun-one-liners/28352/72 "2019-09-16T13:13:56Z")

</div>

> In practical code I would try to work with (ie store) the Cholesky decomposition

Yes, obviously, in this specific case.

> I think that most “textbook” formulas facilitate proof techniques … So preserving them in code is not always a good choice

Certainly - not always. An you’re right, in cases like the above, as soon as a bit of linear algebra is concerned, the actual implementation one would choose is often very different from the textbook - and that’s a bit much to ask from the compiler

However, there are certainly also many cases where the only optimization that will happen is manual extraction of common sub-expression into variables. That, a compiler can do.

Of course it’s not just adding an “ispure” tag to a function - with multiple dispatch, the purity may be hard for the function’s author to guarantee, depending on what code the function uses internally. Still conventions like bang-functions may be sufficient to make this workable.

> YMMV.

Indeed - i would be surprised if there wouldn’t be quite a lot of cases in which optimizations based on compiler knowledge about purity of functions would be beneficial.

My posting wasn’t intended as a feature request in any way, I was just wondering if there was work going on in this direction.

---

<div class="post-metadata">

**Author:** ![tkf](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tkf/32/17635_2.png) [@tkf](https://discourse.julialang.org/u/tkf)\
**Post date:** [September 17, 2019, 12:37am UTC](https://discourse.julialang.org/t/fun-one-liners/28352/73 "2019-09-17T00:37:36Z")

</div>

> [@chakravala](#):
>
> No, but `@pure` is not very well documented

I wouldn’t call this “not very well documented” [https://docs.julialang.org/en/latest/base/base/#Base.@pure](https://docs.julialang.org/en/latest/base/base/#Base.@pure) :

> `@pure` gives the compiler a hint for the definition of a pure function, helping for type inference.
> 
> A pure function can only depend on immutable information. This also means a `@pure` function cannot use any global mutable state, including generic functions. Calls to generic functions depend on method tables which are mutable global state. Use with caution, incorrect `@pure` annotation of a function may introduce hard to identify bugs. Double check for calls to generic functions. This macro is intended for internal compiler use and may be subject to changes.

In particular, I think it is very clear that you can’t use generic functions inside `@pure` functions. Please notice that this is incompatible with your usage:

> [@Marking more standard library methods as pure to enable LLVM optimizations?](https://discourse.julialang.org/t/marking-more-standard-library-methods-as-pure-to-enable-llvm-optimizations/28732/8):
>
> ```julia
> module Grassmann
> @pure binomial(n::Int,k::Int) = Base.binomial(n,k)
> end
> 
> ```
> 
> This replaces the `Base.binomial` method with a local method that is pure.

I think it’s OK to depend on implementation details in some private code or maybe even in public code if you are aware that is an implementation detail and hence cannot rely on the semver promises. For example, [ForwardDiff.jl uses `Threads.atomic_add!` inside `@generated` generator](https://github.com/JuliaDiff/ForwardDiff.jl/blob/c374b69f47095aef60a5486065ddc6fe29c32e9f/src/config.jl#L12-L14) which also is documented that it must be pure. Also, there are (many?) packages using `@generated` to hoist out argument checking to compile time. Since `throw` is a side-effect, this is arguably not a valid use case. CUDAnative.jl is mentioning that it can be a real trouble if you want to use it with GPU: [https://juliagpu.gitlab.io/CUDAnative.jl/man/hacking/#Generated-functions-1](https://juliagpu.gitlab.io/CUDAnative.jl/man/hacking/#Generated-functions-1)

@NHDaly’s JuliaCon talk is a great summary of the current status on this topic and explaining why you can’t use `@pure` or `@generated` in this way safely:

[![](https://global.discourse-cdn.com/julialang/original/3X/2/a/2aa19e0feab4b32c9496c2aeae55dfaa4d19fac2.jpeg "JuliaCon 2019 | If Runtime isn't Funtime: Controlling Compile-time Execution | Nathan Daly") ](https://www.youtube.com/watch?v=JCFej--XER0)

Personally, I often just lift values to type domain as soon as possible and compute things using recursion.

---

<div class="post-metadata">

**Author:** ![greg\_plowman](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/greg_plowman/32/8100_2.png) [@greg\_plowman](https://discourse.julialang.org/u/greg_plowman)\
**Post date:** [September 18, 2019, 7:02am UTC](https://discourse.julialang.org/t/fun-one-liners/28352/74 "2019-09-18T07:02:34Z")

</div>

> [@MrUrq](#):
>
> Simulate the frog problem shown recently on [standupmaths](https://www.youtube.com/watch?v=ZLTyX4zL2Fc) with one line and
> 
> ```julia
> frog(n,cur_lily,steps) = (cur_lily == n) ? steps : frog(n,rand(cur_lily+1:n),steps+1)
> 
> ```
> 
> estimate the mean number of steps needed to jump a 10 step wide river with another
> 
> ```julia
> mean(frog(10,0,0) for _ in 1:1_000_000)
> 
> ```

Ha, I like the frog problem.

Here’s a progression of solutions:

Experimental solution:

```julia
frog2(n) = n==0 ? 0 : frog2(rand(0:n-1)) + 1
mean(frog2(10) for _ in 1:10^8)

```

Analytic solution:

```julia
frog3(n) = n==0 ? 0 : sum(1 + frog3(n-i) for i = 1:n) / n

```

Or with exact rational result:

```julia
frog3(n) = n==0 ? 0 : sum(1 + frog3(n-i) for i = 1:n) // n

```

And for the mathematicians:

```julia
frog4(n) = sum(1/i for i = 1:n)

```

---

<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 19, 2019, 2:09pm UTC](https://discourse.julialang.org/t/fun-one-liners/28352/75 "2019-09-19T14:09:49Z")

</div>

Find indexes of elements in array `b` matching those of array `a`

I wonder if there is a built in method for this?  
`(m-> findfirst(x -> x = m ,b)).(a)`

```julia
b= [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8]
a = [1, 2, 6, 3]

julia> (m-> findfirst(x -> x >= m ,b)).(a)
4-element Array{Int64,1}:
3
4
8
5

```

I use this to bulk plot PDE solutions at particular times `t ` as `f(x,t) vs x`

---

<div class="post-metadata">

**Author:** ![fredrikekre](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/fredrikekre/32/1688_2.png) [@fredrikekre](https://discourse.julialang.org/u/fredrikekre)\
**Post date:** [September 19, 2019, 2:16pm UTC](https://discourse.julialang.org/t/fun-one-liners/28352/76 "2019-09-19T14:16:40Z")

</div>

> [@MatFi](#):
>
> I wonder if there is a built in method for this?

`indexin`:

```julia
julia> b = [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8];
       a = [1, 2, 6, 3];

julia> indexin(a, b)
4-element Array{Union{Nothing, Int64},1}:
 3
 4
 8
 5

```

---

<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 19, 2019, 2:23pm UTC](https://discourse.julialang.org/t/fun-one-liners/28352/77 "2019-09-19T14:23:53Z")

</div>

> [@fredrikekre](#):
>
> `indexin` :

Ok… cool, but is there is also a method returning the indexes of values close to the given ones like :

```julia
b= [-1, 0, 1.2, 2.1, 3.5, 4.87, 5.1, 6, 7, 8]
a = [1, 2, 6, 3]
julia> indexnear(a, b)
4-element Array{Union{Nothing, Int64},1}:
 3
 4
 8
 5

```

here i can simply use `(m-> findfirst(x -> x >= m ,b)).(a)`  
how ever this solution is far from being perfect

**EDIT: Find indexes of elements in array** `b` **close to those in array** `a`  
With the help of this [thread](https://discourse.julialang.org/t/findnearest-function/4143)  
we can do:

`(m-> findmin(abs.(a.-m))[2]).(b)`

---

<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:** [October 16, 2019, 1:18am UTC](https://discourse.julialang.org/t/fun-one-liners/28352/78 "2019-10-16T01:18:20Z")

</div>

Here’s one I found funny,  
`2 ^ 64`

---

<div class="post-metadata">

**Author:** ![StevenSiew](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevensiew/32/218393_2.png) [@StevenSiew](https://discourse.julialang.org/u/StevenSiew)\
**Post date:** [October 16, 2019, 7:06am UTC](https://discourse.julialang.org/t/fun-one-liners/28352/79 "2019-10-16T07:06:03Z")

</div>

Why is it funny?

2 ^ 64

First of all the number 2 has type Int64  
when you raise it to 64th power, it becomes a large number  
but the first bit is about whether it is a negative number

so it represent a negative number in Int64

Also the largest number in Int64 is 2^64 - 1  
just like the largest number in a byte is 2^8 - 1 (aka 255)

When in doubt use BigInt

```julia
julia> big(2)^64
18446744073709551616

```

---

<div class="post-metadata">

**Author:** ![dataDiver](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/datadiver/32/8174_2.png) [@dataDiver](https://discourse.julialang.org/u/dataDiver)\
**Post date:** [October 16, 2019, 10:02am UTC](https://discourse.julialang.org/t/fun-one-liners/28352/80 "2019-10-16T10:02:58Z")

</div>

I am in favour of a solutions thread. That is solutions you discovered on your own and think they are useful enough to share with the community and spark further discussions. It would superset one liners.

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

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