# Seven Lines of Julia (examples sought)

**URL:** <https://discourse.julialang.org/t/seven-lines-of-julia-examples-sought/50416>\
**Category:** General Usage\
**Created:** [November 19, 2020, 7:37am UTC](https://discourse.julialang.org/t/seven-lines-of-julia-examples-sought/50416 "2020-11-19T07:37:29Z")\
**Posts on this page:** 20\
**Page:** 4

<div class="post-metadata">

**Author:** ![Jeff\_Emanuel](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jeff_emanuel/32/15440_2.png) [@Jeff\_Emanuel](https://discourse.julialang.org/u/Jeff_Emanuel)\
**Post date:** [March 12, 2021, 3:57pm UTC](https://discourse.julialang.org/t/seven-lines-of-julia-examples-sought/50416/71 "2021-03-12T15:57:00Z")

</div>

For a fairer comparison:

- Python has mean, median, and geometric\_mean functions that could be employed like the Julia library functions.
- There’s no arbitrary recursion depth here.

---

<div class="post-metadata">

**Author:** ![Albert\_Zevelev](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/albert_zevelev/32/11844_2.png) [@Albert\_Zevelev](https://discourse.julialang.org/u/Albert_Zevelev)\
**Post date:** [March 12, 2021, 4:37pm UTC](https://discourse.julialang.org/t/seven-lines-of-julia-examples-sought/50416/72 "2021-03-12T16:37:23Z")

</div>

Thanks.  
It was a snip from the 1st comment I saw on Twitter.

Language syntax comparison suffer from the same type of problem as language performance comparison:  
it depends on the ability of the person writing the code & on the actual language

The world would be better off if there was a “language elegance game” just like there is a [Benchmarks Game](https://benchmarksgame-team.pages.debian.net/benchmarksgame/index.html).

---

<div class="post-metadata">

**Author:** ![reumle](https://avatars.discourse-cdn.com/v4/letter/r/5daacb/32.png) [@reumle](https://discourse.julialang.org/u/reumle)\
**Post date:** [March 15, 2021, 10:16pm UTC](https://discourse.julialang.org/t/seven-lines-of-julia-examples-sought/50416/73 "2021-03-15T22:16:30Z")

</div>

⁉Wooaah! remarkable! Could you explain how that magic trick works?

```
            Fⁿ(x,n)= ∘(fill(F,n)...)(x) 

```

Thanks!

---

<div class="post-metadata">

**Author:** ![HenriDeh](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/henrideh/32/8316_2.png) [@HenriDeh](https://discourse.julialang.org/u/HenriDeh)\
**Post date:** [March 15, 2021, 10:27pm UTC](https://discourse.julialang.org/t/seven-lines-of-julia-examples-sought/50416/74 "2021-03-15T22:27:32Z")

</div>

∘ is the function composition function. `∘(f,g,h)(x)` turns into `f(g(h(x)))`.  
`fill(F,n)` populates an array with n times the function F. They are composed by ∘ to form the function

`x -> F(F(F(F...F(x)))...)` .

That’s is, you just call it with any argument you like.

See [Essentials · The Julia Language](https://docs.julialang.org/en/v1/base/base/#Base.:%E2%88%98)

---

<div class="post-metadata">

**Author:** ![bradeneliason](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/bradeneliason/32/29031_2.png) [@bradeneliason](https://discourse.julialang.org/u/bradeneliason)\
**Post date:** [March 15, 2021, 11:57pm UTC](https://discourse.julialang.org/t/seven-lines-of-julia-examples-sought/50416/75 "2021-03-15T23:57:22Z")

</div>

Here’s my seven lines (excluding imports). It calculates and plots [pursuit curves](https://mathworld.wolfram.com/PursuitCurve.html) using DifferentialEquations.jl. I’ve renamed the pursuer and pursued to `fox` and `rabbit` for clarity. It’s kind of fun to play around with different paths for the rabbit to take. I have a parameter, `k`, which alters the speed of the fox.

The fourth line beginning `Rx, Ry,...` is a little goofy to fit within the space constraint, but it works and makes what I’m plotting clear as day.

```julia
using Plots, DifferentialEquations, LinearAlgebra

rabbit(t) = [cos(t), sin(t)] # Rabbit Running in a Circle
fox(u, k, t) = k * (rabbit(t) - u) / norm(rabbit(t)-u) # Fox chases rabbit at speed k

prob = ODEProblem(fox, [2.0, 0.0], (0.0, 10), 0.8)
sol = solve(prob, saveat=0.1);
Rx, Ry, Fx, Fy = [getindex.(vcat.(rabbit.(sol.t), sol.u), i) for i=1:4]

plot(Rx, Ry, label="Rabbit", lw=sol.t)
plot!(Fx, Fy, label="Fox", lw=sol.t, aspect_ratio=:equal)

```

![my_seven_lines](https://global.discourse-cdn.com/julialang/original/3X/f/b/fb53321ae940b8458668d38ebf5e1c59077ff1f2.png)

Here’s a bonus animation:  
 ![PursuitCurves_Circle_R02](https://global.discourse-cdn.com/julialang/original/3X/1/7/17784e0c0cf65db38a80cefcc775f8760cedd096.gif)

---

<div class="post-metadata">

**Author:** ![airpmb](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/airpmb/32/7826_2.png) [@airpmb](https://discourse.julialang.org/u/airpmb)\
**Post date:** [March 16, 2021, 12:43am UTC](https://discourse.julialang.org/t/seven-lines-of-julia-examples-sought/50416/76 "2021-03-16T00:43:37Z")

</div>

Don’t forget one of the most evocative tools in Julia-land, the [splat](https://docs.julialang.org/en/v1/manual/faq/#...-splits-one-argument-into-many-different-arguments-in-function-calls), which is needed to take the array-typed output of `fill` and use the elements of that array to populate the individual arguments of `∘`.

---

<div class="post-metadata">

**Author:** ![bradeneliason](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/bradeneliason/32/29031_2.png) [@bradeneliason](https://discourse.julialang.org/u/bradeneliason)\
**Post date:** [March 17, 2021, 1:22am UTC](https://discourse.julialang.org/t/seven-lines-of-julia-examples-sought/50416/77 "2021-03-17T01:22:12Z")

</div>

I had to submit another one. I’m still leaning about the ApproxFun.jl package, so I’m happy to hear your feedback. This my first real trial of this package other than running a few of the examples.

The following 7 lines (excluding imports) calculates deflection, angle, moment, and shear of a uniformly loaded cantilevered beam and plots the results. This uses [ApproxFun.jl](https://github.com/JuliaApproximation/ApproxFun.jl) find to solution of an ODE. The solution to this ODE is a function which defines the vertical displacement of the beam (under certain assumptions). Figure of the setup given below.

![2021-03-16 19_53_23-Bending-Deflection.pdf - Foxit Reader](https://global.discourse-cdn.com/julialang/original/3X/d/f/df9038a606bdfd079295e9dd964b706000e4ab25.png)

The line beginning `B = ...` defines the boundary conditions. It’s a fourth order ODE so there are four boundary conditions. The vertical displacement and first derivative (ie, angle) are both zero at the fixed end of the beam (`leftendpoint`). The moment and shear in the beam (2nd and 3rd) derivatives are zero at the free end of the beam (`rightendpoint`).

The solution is generated on the next line, `v = ...`. The boundary conditions, `B`, are all set to 0 using `zeros(4)...`. The differential equation is defined `E*I*Derivative()^4` and gets set to a uniform load `one(z)` (shown as **q** in the image above).

The rest is just plotting. It’s ugly again to fit into seven lines.

```julia
using ApproxFun, Plots
L, E, I = 12.0, 1.0, 1.0
d = 0..L
z = Fun(identity, d)
B = [[Evaluation(d,leftendpoint,k) for k=0:1]... ; [Evaluation(d,rightendpoint,k) for k=2:3]... ;]
v = [B; E*I*Derivative()^4] \ [zeros(4)..., one(z)]
func_name = zip([v, v', v'', v'''], ["Deflection", "Angle", "Momement", "Shear"])
plot([plot(z, f, title=n, label="") for (f,n) in func_name]..., lw=3)

```

Result:  
 ![my_seven_lines_2_R01](https://global.discourse-cdn.com/julialang/original/3X/d/0/d0e7c460d20cc406b7272bdc37e301f504f056d7.png)

It’s easy enough to change the load function:

```julia
v = [B; E*I*Derivative()^4] \ [zeros(4)..., sin(z)]

```

![my_seven_lines_2_R02](https://global.discourse-cdn.com/julialang/original/3X/b/6/b60e757f3606573df90e75dd1d996c39cdc28863.png)

I haven’t really messed with the units to ensure the solution is scaled correctly, but it does seem to match the analytical solution of the uniformly loaded beam quite well. The comparison:

```julia
plot(z, v, lw=3, label="ApproxFun", title="Deflection | Comparison", legend=:left)
plot!(z-> (z^2)*(z^2 - 4*L*z + 6L^2)/(24*E*I), 0, L, lw=3, ls=:dash, label="Analytical")

```

![my_seven_lines_2_R00](https://global.discourse-cdn.com/julialang/original/3X/9/a/9aa1bde480de8e60798d70133e10102cdb20f1b6.png)

---

<div class="post-metadata">

**Author:** ![JeffreySarnoff](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jeffreysarnoff/32/1980_2.png) [@JeffreySarnoff](https://discourse.julialang.org/u/JeffreySarnoff)\
**Post date:** [March 18, 2021, 1:27am UTC](https://discourse.julialang.org/t/seven-lines-of-julia-examples-sought/50416/78 "2021-03-18T01:27:27Z")

</div>

- eight or nine easily read lines are better than seven munched up lines

---

<div class="post-metadata">

**Author:** ![DhruvaSambrani](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dhruvasambrani/32/21637_2.png) [@DhruvaSambrani](https://discourse.julialang.org/u/DhruvaSambrani)\
**Post date:** [March 30, 2021, 7:51am UTC](https://discourse.julialang.org/t/seven-lines-of-julia-examples-sought/50416/79 "2021-03-30T07:51:14Z")

</div>

Hey!  
I love your code, but you should use

```julia
Fn(n) = reduce(\circ, fill(F, n))(x)
...
Fn(100)[1,1,2,3,5]

```

---

<div class="post-metadata">

**Author:** ![HenriDeh](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/henrideh/32/8316_2.png) [@HenriDeh](https://discourse.julialang.org/u/HenriDeh)\
**Post date:** [March 30, 2021, 8:45am UTC](https://discourse.julialang.org/t/seven-lines-of-julia-examples-sought/50416/80 "2021-03-30T08:45:05Z")

</div>

This is not my code, I saw it on Twitter. But yes it’s true that reducing is faster than splatting. But I think the point here was the clarity of the code not really the performance.

---

<div class="post-metadata">

**Author:** ![FedericoStra](https://avatars.discourse-cdn.com/v4/letter/f/76d3ee/32.png) [@FedericoStra](https://discourse.julialang.org/u/FedericoStra)\
**Post date:** [April 9, 2021, 2:56pm UTC](https://discourse.julialang.org/t/seven-lines-of-julia-examples-sought/50416/81 "2021-04-09T14:56:48Z")

</div>

Your code still wastes memory to create the useless vector `fill(F, n)`. Also, it doesn’t support the case `n=0`. Just do this instead

```julia
Fn(x, n) = foldl((y,_) -> F(y), 1:n; init=x)

```

_Edit_: of course one can use a `StaticArrays.SVector{3}` to sqeeze out the last bit of performance.

---

<div class="post-metadata">

**Author:** ![cscherrer](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/cscherrer/32/7631_2.png) [@cscherrer](https://discourse.julialang.org/u/cscherrer)\
**Post date:** [April 9, 2021, 5:51pm UTC](https://discourse.julialang.org/t/seven-lines-of-julia-examples-sought/50416/82 "2021-04-09T17:51:05Z")

</div>

Just slightly over, but here’s a user-defined linear regression in Soss.jl:

```julia
julia> using Soss, MeasureTheory, SampleChainsDynamicHMC

julia> a = -0.2; b=2.0;

julia> x = randn(100); y = a .+ b .* x;

julia> m = @model x begin
       a ~ Normal()
       b ~ Normal()
       y ~ For(x) do xj Normal(a + b * xj, 1) end
       end;

julia> sample(DynamicHMCChain, m(x=x) | (;y=y))
4000-element MultiChain with 4 chains and schema (b = Float64, a = Float64)
(b = 1.985±0.097, a = -0.207±0.11)

```

---

<div class="post-metadata">

**Author:** ![Albert\_Zevelev](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/albert_zevelev/32/11844_2.png) [@Albert\_Zevelev](https://discourse.julialang.org/u/Albert_Zevelev)\
**Post date:** [April 9, 2021, 8:09pm UTC](https://discourse.julialang.org/t/seven-lines-of-julia-examples-sought/50416/84 "2021-04-09T20:09:53Z")

</div>

> [@DNF](#):
>
> It’s unsafe, it’s type piracy, and it’s pretty neat.

It’s also standard notation for function iteration in the Dynamical Systems literature.  
I agree it’s super neat!

Can you help me understand, what does “unsafe” & “type piracy” mean (in general & in this context)?

Btw, for composition I define a `Nest(f,x0,n)` function [like Mathematica](https://reference.wolfram.com/language/ref/Nest.html):

```julia
Nest(f,x0,n) = (n == 0) ? x0 : (f∘Nest)(f,x0,n-1)
import Base.^;
h^(n::Integer) = x0 -> foldl( (x, _) -> h(x), 1:n; init = x0)

```

---

<div class="post-metadata">

**Author:** ![jzr](https://avatars.discourse-cdn.com/v4/letter/j/eb9ed0/32.png) [@jzr](https://discourse.julialang.org/u/jzr)\
**Post date:** [April 9, 2021, 8:24pm UTC](https://discourse.julialang.org/t/seven-lines-of-julia-examples-sought/50416/85 "2021-04-09T20:24:36Z")

</div>

[Type piracy](https://docs.julialang.org/en/v1/manual/style-guide/#Avoid-type-piracy) is when a module defines a method but neither the function nor any of the method’s parameter types are created by that module.

---

<div class="post-metadata">

**Author:** ![Albert\_Zevelev](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/albert_zevelev/32/11844_2.png) [@Albert\_Zevelev](https://discourse.julialang.org/u/Albert_Zevelev)\
**Post date:** [April 9, 2021, 8:29pm UTC](https://discourse.julialang.org/t/seven-lines-of-julia-examples-sought/50416/86 "2021-04-09T20:29:38Z")

</div>

Thanks, but what does that mean in this context?

---

<div class="post-metadata">

**Author:** ![jzr](https://avatars.discourse-cdn.com/v4/letter/j/eb9ed0/32.png) [@jzr](https://discourse.julialang.org/u/jzr)\
**Post date:** [April 9, 2021, 9:05pm UTC](https://discourse.julialang.org/t/seven-lines-of-julia-examples-sought/50416/87 "2021-04-09T21:05:11Z")

</div>

```julia
Base.:^(f::Function, n) = n==1 ? f : f ∘ f^(n-1)

```

That snippet uses `^` and `Function`, but both of those come from another module, Base. It would not be type piracy to define

```julia
struct CustomCounter end

Base.:^(f::Function, n::CustomCounter) = n==1 ? f : f ∘ f^(n-1)

```

because `CustomCounter` is defined in this module.

---

<div class="post-metadata">

**Author:** ![FedericoStra](https://avatars.discourse-cdn.com/v4/letter/f/76d3ee/32.png) [@FedericoStra](https://discourse.julialang.org/u/FedericoStra)\
**Post date:** [April 9, 2021, 9:13pm UTC](https://discourse.julialang.org/t/seven-lines-of-julia-examples-sought/50416/88 "2021-04-09T21:13:28Z")

</div>

It’s also super slow and wasteful

```julia
julia> @time @btime (F^(10^3))([1,1,2,3,5])
  660.172 μs (2001 allocations: 218.89 KiB)
 10.475864 seconds (29.82 M allocations: 3.087 GiB, 4.50% gc time, 0.24% compilation time)
3-element Vector{Float64}:
 2.089057949736859
 2.089057949736859
 2.089057949736859

```

and doomed to fail miserably

```julia
julia> (F^(10^5))([1,1,2,3,5])
...

```

_Bonus_: if one is really concerned about the type piracy, then

```julia
(f::Function)↑(n::Integer) = x0 -> foldl((x, _) -> f(x), 1:n; init = x0)

```

is a suggestive alternative (`↑` is `\uparrow`).

_Edit_: in the first code snippet, `@time @btime` is a typo. The intended code was just `@time`, to take into consideration also the compilation time, instead of `@btime`.

---

<div class="post-metadata">

**Author:** ![Albert\_Zevelev](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/albert_zevelev/32/11844_2.png) [@Albert\_Zevelev](https://discourse.julialang.org/u/Albert_Zevelev)\
**Post date:** [April 9, 2021, 9:20pm UTC](https://discourse.julialang.org/t/seven-lines-of-julia-examples-sought/50416/89 "2021-04-09T21:20:21Z")

</div>

Try my version w/ ‘foldl’

---

<div class="post-metadata">

**Author:** ![FedericoStra](https://avatars.discourse-cdn.com/v4/letter/f/76d3ee/32.png) [@FedericoStra](https://discourse.julialang.org/u/FedericoStra)\
**Post date:** [April 9, 2021, 9:21pm UTC](https://discourse.julialang.org/t/seven-lines-of-julia-examples-sought/50416/90 "2021-04-09T21:21:32Z")

</div>

Yes your version with `foldl` is perfectly fine!

---

<div class="post-metadata">

**Author:** ![mschauer](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mschauer/32/13946_2.png) [@mschauer](https://discourse.julialang.org/u/mschauer)\
**Post date:** [April 9, 2021, 9:30pm UTC](https://discourse.julialang.org/t/seven-lines-of-julia-examples-sought/50416/91 "2021-04-09T21:30:30Z")

</div>

I like [Pink noise](https://en.wikipedia.org/wiki/Pink_noise). It’s is Gaussian noise with power spectral density _1/fᵅ_. One can sample it with the inverse Fourier transform

```julia

# Make pink noise
using FFTW, Statistics
function pinknoise(m, n) 
    A = real(ifft((Complex{Float64}[i+j==2 ? 0. : (randn()+randn()*im)/sqrt((sin((i-1)*pi/m)^2 + sin((j-1)* pi/n)^2)) for i in 1:m, j in 1:n])))
    real(A)/std(A)
end
A = pinknoise(500, 500)

```

![test](https://global.discourse-cdn.com/julialang/original/3X/1/0/10e048e49a182fa72f567ee279f6d7ea456eb9f1.jpeg)

It most spectacular property is that it is invariant under conformal mappings, functions that locally preserves angles, but not necessarily lengths, for example the map `x + y*im -> ((x + y*im)/33)^2`.

```julia
# Make conformal map
getindexfc(A, i, j) = A[mod1(ceil(Int, i), size(A,1)), mod1(ceil(Int, j), size(A,2))]
finv(x) = reim(sqrt(x[1] + x[2]*im)*33) # use inverse for look-up
cfmap(A) = map(CartesianIndices(size(A))) do I
     getindexfc(A, finv(I)...) 
end

```

This is how it acts on a grid matrix `G`:

```julia
[G cfmap(G)]

```

 ![test](https://global.discourse-cdn.com/julialang/original/3X/4/f/4fd73d338f92a171ff6892eee57b7c2b7f8a9b2f.png)

And here with pink noise

```julia
[A cfmap(A)]

```

![animation](https://global.discourse-cdn.com/julialang/original/3X/8/a/8a9fb26a4af5752c8f85d5f083dcc4aa6f23b37f.gif)

PS: I took a bit extra effort to make it tiling, try `[A A A; A A A; A A A]`

[Previous page](https://discourse.julialang.org/t/seven-lines-of-julia-examples-sought/50416.md?page=3)

[Next page](https://discourse.julialang.org/t/seven-lines-of-julia-examples-sought/50416.md?page=5)
