Julia Community 🟣

Vinod V
Vinod V

Posted on • Updated on

10 Julia Recipes You Can't Miss

a.Accept arbitray number of function arguments

function sum1(a, remaining...)
    sm = a + sum(remaining)
    println(sm)
end

sum1(1, 2, 3, 4,5)
sum1(1)
sum1(1,2,3)
Enter fullscreen mode Exit fullscreen mode

b.You can search and replace a simple text pattern in a string using the replace() method.

stri = "I scream, you scream, we all scream for ice cream."
stri = replace(stri, "scream" => "cry")
println(stri)
stri = "I scream, you scream, we all scream for ice cream."
replace(stri, "scream"=>uppercase) #replace scream by SCREAM
Enter fullscreen mode Exit fullscreen mode

c. Filtering a list based on some condition

temp = [56, 49, 50, 55, 53, 52, 60, 60, 42, 54]

# Only the elements that are greater than 50
filtered = [item for item in temp if item > 50]
print(filtered)

filtered = filter(>(50), temp)

filtered = filter(temp) do x
    x > 50
end
Enter fullscreen mode Exit fullscreen mode

d.Unpack tuple to a list of variables

temp1 = (45, 51, 43, 49, 47)
a, b, c, d, e = temp1
print(a)
print(d)

stri = "Money"
c1, c2, c3, c4, c5 = stri

t = (a=1, b="hello", c = 3.14) #named tuple
(; a, c) = t; @show a; @show c; #a = 1,c = 3.14,b undefined
Enter fullscreen mode Exit fullscreen mode

e.Dictionary comprehension in Julia

marks = Dict("Ram" => 60, "Shyam" => 33, "Manik" => 64,"Mani" => 76, "Hema" => 84)

more_than_55 = Dict(key => value for (key, value) in marks if value > 60)
println(more_than_55)

names = Set(["Ram", "Hema", "Mani","Manik"])
selected = Dict(key => value for (key, value) in marks if key in names)
println(selected)
Enter fullscreen mode Exit fullscreen mode

f.Iterating in Reverse in Julia

for i in reverse(1:5)
  print(i)
end

r = reverse("Julia")
"ailuJ"

for i in 1:length(r)
  print(r[reverseind("Julia", i)])
end
Enter fullscreen mode Exit fullscreen mode

g.Padding Strings in Julia

str = "Julia's syntax is good"
println(lpad(str, 40, '*'))
println(rpad(str, 40, '*'))
Enter fullscreen mode Exit fullscreen mode

h.Return multiple values from a function

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

countries = retMultipleValues()
println(countries)
Enter fullscreen mode Exit fullscreen mode

i. Creating and Writing to a Text File in Julia

fid = open("abc.txt", "x") #"x" flag ensures that the file is created only if it does not already exist. 
write(fid, "Hello Julia")
close(fid)

open("def.txt", "w") do fid #no need for close statement
    write(fid, "Hey")
end

#Read a text file line by line
for line in eachline("my_file.txt")
    print(line)
end

#most compact
foreach(println,eachline("my_file.txt"))

Enter fullscreen mode Exit fullscreen mode

j. Parse date string to DateTime object

using Dates

dstr = "2023-07-03"
println(typeof(dstr))

date_time = DateTime(dstr, "yyyy-mm-dd")
println(date_time)
println(typeof(date_time))
Enter fullscreen mode Exit fullscreen mode

New trick suggested by reviewers:
k. Make a 10-element vector of random named tuples

points = [(x=rand(), y=rand()) for i in 1:10]
distances = [sqrt(p.x^2 + p.y^2) for p in points if p.x > p.y]
#distances = [hypot(p.x , p.y) for p in points if p.x > p.y]
Enter fullscreen mode Exit fullscreen mode

l. Unpacking of tuples of varying sizes (Julia version 1.9)

julia> a, b..., c = (1, 2, 3, 4)
(1, 2, 3, 4)

julia> a
1

julia> b
(2, 3)

julia> c
4

Enter fullscreen mode Exit fullscreen mode

m. Convert a number array to string

julia> r = join([1,2,3.1], ", ")
"1.0, 2.0, 3.1"
Enter fullscreen mode Exit fullscreen mode

n. Round a float to integer

julia> round(Int, 12.5) == Int(trunc(12.5))
true
Enter fullscreen mode Exit fullscreen mode

o. To parse a binary string to integer

parse(Int, "1011", base=2) 
Enter fullscreen mode Exit fullscreen mode

p. To create a random binary string

 join(rand(['1','0'],10))
Enter fullscreen mode Exit fullscreen mode

Top comments (10)

Collapse
 
petrkryslucsd profile image
Petr Krysl

Re (i): I personally like this pattern (takes care of the closing automatically):

open("def.txt", "w") do fid
    write(fid, "Hey")
end
Enter fullscreen mode Exit fullscreen mode
Collapse
 
vinodv profile image
Vinod V

Updated in the blog

Collapse
 
edwcarney profile image
Edward Carney

In item k., correct use of hypot, to make it equivalent to the sqrt() method, is hypot(p.x, p.y).

The one with a '+' returns the absolute value of the argument.

Collapse
 
vinodv profile image
Vinod V

Corrected

Collapse
 
hungpham3112 profile image
hungpham3112

Can you check again the code format?

Collapse
 
vinodv profile image
Vinod V • Edited

Done. I have replaced single tilde by three tildes followed by Julia. Now formatting is OK. Tilde code block is available as a default option in forem. It is not working properly.

Collapse
 
petrkryslucsd profile image
Petr Krysl

Nice post!

I think what you mean is "backtick" (`). Tilda is ~.

Regards,

P

Thread Thread
 
vinodv profile image
Vinod V

True

Collapse
 
hungpham3112 profile image
hungpham3112

Take a note at index of code block

Thread Thread
 
vinodv profile image
Vinod V • Edited

I n the source I have numbered it properly. Is this a bug in forem software? I have changed indexing.