Prologue: Departure to Neverland
Once upon a time, in the mystical world of terminals, we find ourselves tagging along on a Peter Pan-themed odyssey, soaring across the skies of Neverland. Our quest? To discover the magic similarities and differences of the unique spirits of Bash
, Lua
, Python
, and Rust
.
Chapter 1: Aboard the Jolly Roger with Bash and Lua
Under the moonlit sky, we join Captain Hook on the Jolly Roger, navigating the traditional seas of Bash and Lua. Like seasoned sailors chanting an age-old shanty, these languages use for loops as their trusted compass.
Bash - The Captain's Command:
#!/bin/bash
sum_odd_int_array() {
local sum=0
for x in "$@"; do
if (( x % 2 != 0 )); then
(( sum+=x ))
fi
done
echo $sum
}
array=(1 2 3 4 5)
sum_odd_int_array ${array[@]}
Lua - The First Mate's Chant:
function sum_odd_int_array(array)
local sum = 0
for _, x in ipairs(array) do
if x % 2 ~= 0 then
sum = sum + x
end
end
return sum
end
local array = {1, 2, 3, 4, 5}
print(sum_odd_int_array(array))
Chapter 2: Tinker Bell's Python Whispers
In the heart of Neverland, Tinker Bell whisks us away, revealing the wonders of Python. She shows us two paths: one trodden by many, and the other, a secret trail lit by her magical glow.
The Beaten Path - Traditional For Loop:
def sum_odd_int_array_for_loop(array: list[int]) -> int:
sum = 0
for x in array:
if x % 2 != 0:
sum += x
return sum
array = [1, 2, 3, 4, 5]
print(sum_odd_int_array_for_loop(array))
Tinker Bell's Enchanted Trail - Comprehension:
def sum_odd_int_array(array: list[int]) -> int:
return sum(x for x in array if x % 2 != 0)
array = [1, 2, 3, 4, 5]
print(sum_odd_int_array(array))
Chapter 3: The Lost Boys' Rusty Innovations
Deep in Neverland's forests, the Lost Boys unveil their secret: a marvel of Rust. First, a familiar structure, echoing the old ways. Then, a creation so ingenious, it seemed woven from the threads of the future.
The Olden Design - Traditional For Loop:
fn sum_odd_int_array_for_loop(array: &[i32]) -> i32 {
let mut sum = 0;
for &x in array {
if x % 2 != 0 {
sum += x;
}
}
sum
}
fn main() {
let array = [1, 2, 3, 4, 5];
println!("{}", sum_odd_int_array_for_loop(&array));
}
The Future Woven - Iterator Method:
fn sum_odd_int_array(array: &[i32]) -> i32 {
array.iter().filter(|&&x| x % 2 != 0).sum()
}
fn main() {
let array = [1, 2, 3, 4, 5];
println!("{}", sum_odd_int_array(&array));
}
Epilogue: Magic in the Code
From the steady chants of Bash and Lua to the whimsical whispers of Python and the ingenious creations of Rust, each language brings its own spellbinding qualities. We're reminded of the magic and wonder that each language holds.
As ageless programmers on a Neverland odyssey, we discover the art of transcending traditional loops, delving into the allure of modern programming languages and their captivating syntactic sugar.
In this Neverland of code, the adventure never ends, and with each line written, we continue to weave our own magical tales.
Until then
, keep on coding with πͺ andπͺs.
Top comments (24)
If you really want "The quest?" to be "To discover the magic similarities and differences of the unique spirits of Bash, Lua, Python, and Rust." you need to rewrite all of the provided code examples in order to make them show actual deep insight into the "spirits" of these languages. A nice story-telling is one thing, but to dive into a "spirit" of a programming language requires a deep understanding of it you have missed to integrate into the provided code examples and explain in the text of the story.
If the goal of the quest is to sum all odd numbers in some range I suggest to use a much larger range as for example from 1 to 111 in order to be able to demonstrate the differences between the languages and focus then on the actual goal of printing the sum instead of choosing an unnecessary detour by using a function in first place.
Let's demonstrate what I am speaking about comparing bash, lua and python summing odd numbers in range from 1 to 111, both 1 and 111 included into the sum:
-- Bash "spirit" is to use the mechanisms of substitutions all prefixed by the "$" sign. So bash is about DOLLARs, pipes and different kinds of braces.
-- Lua "spirit" is to focus on small size of the executable, so there is for example no support for unary "+=" as it would require more code for the parser
-- Python "spirit" is to come with "batteries included", since the ready to use sum() and range() functions. Python "spirit" is also to exclude the upper value from being part of the created range, so you need to specify 112 as upper range limit to include 111 in the range.
Sorry, but I am not (yet) familiar with the "spirit" and all the specifics of Rust (the reason why I don't provide a Rust code example), so maybe someone else with deep understanding of Rust can help out?
NOTICE that also Bash is equipped with the modern way of "hiding" the actual loop you seem not to be aware of providing the bash example code without mentioning this like you mention it in the context of Python and Rust.
WoW! That is awesome. Perhaps another article. I primary use Python π and Rust π¦, Bash and Lua π are secondary.
My main goal was not to show the power or effectiveness or to compare the languages. My aim is to show that even though we can write some of code very similar, some languages have their syntactic sugar π€.
With the goal of filtering numbers and adding, is it possible to use Bash modern way of βhiding" loops? Did I miss Bash syntactic sugar?
Notice, that Bash is only the Captain and comes with many other crew members to cover a wider range of uses. Take a look at the core of the idea behind oOo ( the appropriate github project is linked in my profile ) which made me walk away from Python to Lua and currently away from Lua to Bash and its helpers in order to arrive at an own way of doing things combining comments, explanations and code. The quest programmed the oOo way could for example look like:
The English language is powerful enough as a programming language ... you only need to learn how to use it for such purpose and adapt it to your specific vocabulary to make things easier for you. Which programming language does then create the executable starts then be of much lesser importance and actual does not matter anymore.
Nice! Are you using LLMs under the hood?
Currently not ... the idea of oOo I am after is so different from what is already there that LLMs "knowing" only about the past and (at the moment) not (yet) capable of learning from own experience are of no use. I have been making fast progress in the first half of 2023 in my programming with help of ChatGPT only to finally notice that the journey goes nowhere ... Now, more experienced, I am back on the pure oOo path and excited about where it will lead me. It seems that except Rebol (see sassenrath.com/computing.html ) related there are no other attempts towards what oOo is actual after.
I am cheering π£ for your success. You are awesome ππΏ
Your way of enriching "boring" subject of programming with very interesting images, conveying emotions and relating to well known stories aligns very well with what oOo is after. Where do you get the images you use in your articles? Self-done?
I use mostly openjourney, bingβs Dalle-E, and Adobeβs Firefly.
The example how to "hide" the loop while adding all array values is given in the above provided code. The much more interesting question in this context is WHY do you want to have in another programming language structures you know about from using Python or Rust instead of diving deep enough into the spirit of the other language to see that they are maybe not really a better way of doing things? Is "modern" always better? Going up the hierarchy of abstraction has also downsides ... "modern" is for sure not always the better option for many different reasons. Another aspect to consider in this context is code readability. Explicit loops are easier to spot and understand and not necessarily slower compared to the "hidden" way of specifying them.
Oh no! I am not suggesting for better-ness. I just thought I missed something in Bash π
Below how Captain Bash delegates filtering of an array to the Grep member of his crew:
The "trick" here is that all odd numbers end with one of 1,3,5,7,9, so there is no need for calculation of modulo and an
if
condition.That is another level ππΏπ₯³ and pure genius.
For me what makes the shell something unique are pipes:
A killer one-linner proves that
π€―Nice. Is there similar that takes a sequence of even and odd numbers and only sum odds?
yes:
seq 9 | awk '{($1 % 2 ? sum+=$1 : 0)} END { print sum}'
Now that blows my mind π€―. ππ Is
awk
not programming language by itself?Maybe worth to mention in this context is the obesity of the Python "spirit" compared to the slim and lightweight "spirit" of Lua (check out the download sizes for the Lua and Python interpreter to see yourself how "obese" Python is when compared to Lua).
Below a code example with pre-defined functions in Lua allowing to achieve the code brevity of Python for the task of summing odd numbers in the given range. Is skipping this small piece of preliminary code worth a download size beyond 15 MByte for the interpreter?
The code above demonstrates how Lua copes with lowering memory requirements providing a mechanism comparable to Python generator functions. Notice that Lua supports multiline comments (you can even nest them using
--[=[ multiline comment of higher order --[[ with lower order comment ]] inside it ]=]
)Nice ππΎ. I worked with Lua π primary with my kids as they are Roblox lovers. I have not yet dive into its power than simple scripts.
Sir, your writing style is brilliant
Thank you, Antonov. I am attempting a story like telling of concepts π«’ I love telling stories.
Great Story, Like it π₯
I am glad you did πͺππΏ
Replace in the bash code the unnecessary double echoing
echo $(sum_odd_int_array "${array[@]}")
with
sum_odd_int_array ${array[@]}
Nice catch! ππΎ The function already echo instead of
return
π«£. And were we to return then we are limited to 0-255 πThank you ππΎ for reading and catching my blunder π€