DEV Community

Cover image for To Code and Beyond: A Neverland Adventure in Bash, Lua, Python, and Rust
Prayson Wilfred Daniel
Prayson Wilfred Daniel

Posted on • Edited on

To Code and Beyond: A Neverland Adventure in Bash, Lua, Python, and Rust

ship

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[@]}
Enter fullscreen mode Exit fullscreen mode

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))
Enter fullscreen mode Exit fullscreen mode

peter

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))
Enter fullscreen mode Exit fullscreen mode

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))
Enter fullscreen mode Exit fullscreen mode

rust

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));
}
Enter fullscreen mode Exit fullscreen mode

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));
}
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
ooosys profile image
oOosys • Edited

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:   a=({1..111..2});IFS=+;echo "$((${a[*]}))"
Lua:    s=0;for i=1,111,2 do s=s+i end;print(s)
Python: print(sum(range(1,112,2)))
Enter fullscreen mode Exit fullscreen mode

-- 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.

Collapse
 
proteusiq profile image
Prayson Wilfred Daniel • Edited

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?

Collapse
 
ooosys profile image
oOosys

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:

Print to Β«%stdout%Β»  a  Β«*sum*Β» of all Β«-oddNumbers-Β» occuring in the list  Β«_1 2 3 4 5 _Β».
Enter fullscreen mode Exit fullscreen mode

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.

Thread Thread
 
proteusiq profile image
Prayson Wilfred Daniel • Edited

Nice! Are you using LLMs under the hood?

Thread Thread
 
ooosys profile image
oOosys

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.

Thread Thread
 
proteusiq profile image
Prayson Wilfred Daniel

I am cheering πŸ“£ for your success. You are awesome πŸ™ŒπŸΏ

Thread Thread
 
ooosys profile image
oOosys • Edited

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?

Thread Thread
 
proteusiq profile image
Prayson Wilfred Daniel
Collapse
 
ooosys profile image
oOosys

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.

Thread Thread
 
proteusiq profile image
Prayson Wilfred Daniel

Oh no! I am not suggesting for better-ness. I just thought I missed something in Bash 😊

Thread Thread
 
ooosys profile image
oOosys • Edited

Below how Captain Bash delegates filtering of an array to the Grep member of his crew:

a=({1..111..1}); 
IFS=$'\n'; A=( $( echo "${a[*]}" | grep --regexp='[13579]$' ) )
IFS=+; echo "$((${A[*]}))" 
Enter fullscreen mode Exit fullscreen mode

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.

Thread Thread
 
proteusiq profile image
Prayson Wilfred Daniel • Edited

That is another level πŸ™ŒπŸΏπŸ₯³ and pure genius.

Collapse
 
voyeg3r profile image
SΓ©rgio AraΓΊjo

For me what makes the shell something unique are pipes:

seq -s+ 1 2 5 | bc
Enter fullscreen mode Exit fullscreen mode

A killer one-linner proves that

Collapse
 
proteusiq profile image
Prayson Wilfred Daniel

🀯Nice. Is there similar that takes a sequence of even and odd numbers and only sum odds?

Collapse
 
voyeg3r profile image
SΓ©rgio AraΓΊjo

yes:

seq 9 | awk '{($1 % 2 ? sum+=$1 : 0)} END { print sum}'

Thread Thread
 
proteusiq profile image
Prayson Wilfred Daniel • Edited

Now that blows my mind 🀯. 😍🎊 Is awk not programming language by itself?

Collapse
 
ooosys profile image
oOosys

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?

#!/bin/lua
function rangeGenerator(...) --[[
    Use in case of large arrays to avoid allocation of memory holding the entire range if 
    your goal is to iterate/loop over the range values only                         ]]
    local n_args = select("#", ...)
    local increment = 1
    if n_args == 1 then     from, to = 0, ...
    elseif n_args == 2 then from, to = ...
    elseif n_args == 3 then from, to, increment = ...
    else error"range requires 1-3 arguments" end
    local i = from
    return function()
    if i > to then return end --[[ NOTICE that the 'to' value will be included in the range ]]
        local prev_i = i
        i = i + increment
        return prev_i
    end
end
function range(...) --[[ 
    Returns a TABLE holding all of the generated range values, so use it only for small
    table sizes if the goal is to iterate over the table values, else use rangeGenerator() ]]
    local n_args = select("#", ...)
    local increment = 1
    if      n_args == 1 then from, to = 0, ...
    elseif  n_args == 2 then from, to = ...
    elseif  n_args == 3 then from, to, increment = ...
    else error"range requires 1-3 arguments" end
    r={};for i=from,to,increment do r[#r+1]=i end
    return r
end
function sumRange(...)
    s=0;for i in rangeGenerator(...) do s=s+i end
    return s
end
function sum(a)
    s=0; for _,v in ipairs(a) do s=s+v end
    return s
end

s=0;for i=1,111,2 do s=s+i end;print(s)
print(sumRange(1,111,2))
print(sum(range(1,111,2)))
Enter fullscreen mode Exit fullscreen mode

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 ]=] )

Collapse
 
proteusiq profile image
Prayson Wilfred Daniel • Edited

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.

Collapse
 
antonov_mike profile image
Antonov Mike

Sir, your writing style is brilliant

Collapse
 
proteusiq profile image
Prayson Wilfred Daniel

Thank you, Antonov. I am attempting a story like telling of concepts 🫒 I love telling stories.

Collapse
 
tharakamts profile image
Tharaka Sandaruwan

Great Story, Like it πŸ”₯

Collapse
 
proteusiq profile image
Prayson Wilfred Daniel

I am glad you did πŸͺπŸ™πŸΏ

Collapse
 
ooosys profile image
oOosys

Replace in the bash code the unnecessary double echoing
echo $(sum_odd_int_array "${array[@]}")
with
sum_odd_int_array ${array[@]}

Collapse
 
proteusiq profile image
Prayson Wilfred Daniel • Edited

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 🀭