# FreeBSD Dynamic Programming



## Deleted member 70435 (Apr 8, 2022)

If you’ve been programming for long enough, you’ve probably heard the term dynamic programming. Often a key subject in technical interviews, the idea will also come up in design review meetings or regular interactions with fellow developers. This essay will examine what dynamic programming is and why you would use it. I’ll be illustrating this concept with  specific code examples in Swift, but the concepts I introduce can be applied to your language of choice. Let’s begin!
A way of thinking​Unlike specific coding syntax or design patterns, dynamic programming isn’t a particular algorithm but a *way of thinking*. Therefore, the technique takes many forms when it comes to implementation.

The main idea of dynamic programming is to consider a significant problem and break it into smaller, individualized components. When it comes to implementation, optimal techniques rely on data storage and reuse to increase algorithm efficiency. As we’ll see, many questions in software development are solved using various forms of dynamic programming. The trick is recognizing when optimal solutions can be devised using a simple variable or require a sophisticated data structure or algorithm.

For example, code variables can be considered an elementary form of dynamic programming. As we know, a variable’s purpose is to reserve a specific place in memory for a value to be recalled later.


```
//non-memoized function
func addNumbers(lhs: Int, rhs: Int) -> Int {
   return lhs + rhs
}

//memoized function
func addNumbersMemo(lhs: Int, rhs: Int) -> Int {
   let result: Int = lhs + rhs
     return result
}
```

While addNumbersMemo above does provide a simple introduction, the goal of a dynamic programming solution is to preserve previously seen values because the alternative could either be inefficient or could prevent you from answering the question. This design technique is known as *memoization*.
A brute force approach​Our first approach involves looking at the first value, then reviewing each subsequent value to determine if it will provide the *difference* needed to solve the question. For example, once our algorithm checks the value of the first array item, 8, it will then scan the remaining values for 3 (e.g., 11 – 8 = 3). However, we can see the value of 3 doesn’t exist, so the algorithm will repeat the same process for the next value (in our case, 10) until it finds a successful matching pair. Without going into the details of big-O notation, we can assume this type of solution would have an average runtime of O(n ^ 2)time or greater, mainly because our algorithm works by comparing each value with every other value. In code, this can be represented as follows:


```
let sequence = [8, 10, 2, 9, 7, 5]

//non-memoized version - O(n ^ 2)
func pairNumbers(sum: Int) -> (Int, Int) {
 
    for a in sequence {
            let diff = sum - a
 
            for b in sequence {
                if (b != a) && (b == diff) {
                    return (a, b)
                }
            }
    }
    return (0, 0)
}
```

A memoized approach​Next, let’s try a different approach using the idea of memoization. Before implementing our code, we can brainstorm how storing previously seen values will help streamline the process. While using a standard array is feasible, a set collection object (also referred to as a hash table or hash map) could provide an optimized solution.


```
//memoized version - O(n + d)
func pairNumbersMemoized(sum: Int) -> (Int, Int) {
 
    var addends = Set<Int>()
 
    for a in sequence {
            let diff = sum - a
 
        if addends.contains(diff) { //O(1) - constant time lookup
                    return (a, diff)
            }
            //store previously seen value
            else {
                addends.insert(a)
            }
      }
 
    return (0, 0)
 }
```

Using a memoized approach, we’ve improved the algorithm’s average run time efficiency to O(n + d) by adding previously seen values to a set collection object. Those familiar with hash-based structures will know that item insert and retrieval occurs in O(1) – constant time. This further streamlines the solution, as the set is designed to retrieve values in an optimized way regardless of size.
The Fibonacci sequence​When learning various programming techniques, one topic that comes to mind is recursion. Recursive solutions work by having a model that refers to itself. As such, recursive techniques are implemented through algorithms or data structures. A well-known example of recursion can be seen with the Fibonacci sequence—a numerical sequence made by adding the two preceding numbers (0, 1, 1, 2, 3, 5, 8, 13, 21, etc):


```
public func fibRec(_ n: Int) -> Int {
        if n < 2 {
            return n
        } else {
            return fibRec(n-1) + fibRec(n-2)
        }
 }
```

When examined, our code is error-free and works as expected. However, notice a few things about the performance of the algorithm:



*Positions (n)**fibRec() – Number of times called**2**1**4**5**10**109**15**1219*


As shown, there’s a significant increase in the number of times our function is called. Similar to our previous example, the algorithm’s performance decreases exponentially based on the input size. This occurs because the operation does not store previously calculated values. Without access to stored variables, the only way we can obtain the required (preceding) values is through recursion. Assuming this code is used in a production setting, the function could introduce bugs or performance errors. Let’s refactor the code to support a memoized approach:


```
func fibMemoizedPosition(_ n: Int) -> Int {

        var sequence: Array<Int> = [0, 1]
        var results: Int = 0
        var i: Int = sequence.count
 
        //trivial case
        guard n > i else {
            return n
        }
 
        //all other cases..
        while i <= n {
            results = sequence[i - 1] + sequence[i - 2]
            sequence.append(results)
            i += 1
        }
 
        return results
}
```

This revised solution now supports memoization through the use of stored variables. Notice how the refactored code no longer requires a recursive technique. The two most previous values are added to a result, which is appended to the main array sequence. Even though the algorithm’s performance still depends on the sequence size, our revisions have increased algorithmic efficiency to O(n) – linear time. In addition, our iterative solution should be easier to revise, test and debug since a single function is added to the call stack, thus reducing complexities with memory management and object scope.
Conclusion​We’ve learned that dynamic programming isn’t a specific design pattern as it is a way of thinking. Its goal is to create a solution to preserve previously seen values to increase time efficiency. While examples include basic algorithms, dynamic programming provides a foundation in almost all programs. This includes the use of simple variables and complex data structures.


----------



## ralphbsz (Apr 8, 2022)

What does this have to do with FreeBSD internal development?

And: The idea of caching results is old and well known. So much so that some programming languages have it in their libraries (see Python's memoize).


----------



## kpedersen (Apr 8, 2022)

This approach can also a little problematic with multi-threaded code.

I can certainly see that it does have merit for some use-cases however but yeah, ralphbsz is right, this thread is probably better off in the Userland Programming and Scripting section of the forum .


----------



## Deleted member 70435 (Apr 8, 2022)

certainly, you haven't understood yet. that's an idea clearly, you can have a vision of how to implement something. certainly in another session. of course it has nothing to do with FreeBSD, but you would develop something without an idea maybe not, maybe yes you read the manual of FreeBSD.. something so simple but it makes some people really understand,

what you don't understand here, is how it's going to be implemented, that's in the algorhythmic notion, in FreeBSD


----------



## kpedersen (Apr 8, 2022)

Dimitri Chuikov said:


> what you don't understand here, is how it's going to be implemented, that's in the algorhythmic notion, in FreeBSD


Are you saying this sort of code design should go into FreeBSD itself? I don't think that is a bad idea but it might take some time to find specific areas to start with where it might be a benefit (perhaps logic for dealing with filesystem nodes? file descriptors? task scheduling?). For that, the developers mailing list (and just analysing the code) will be useful.


----------



## mer (Apr 8, 2022)

Data + algorithms = programs

No offense to the OP, but all programming is a way of thinking.
Object Oriented?  A way of thinking.  You can implement it in C, C++, Java, whatever you want.
Dynamic programming seems to be the current iteration of past thinking.
I've seen a lot of these concepts presented in relation to a langague: Swift, Go, Rust, Java, JavaScript, Python, etc.

I realize the first example is trivial, but I think a good compiler would result in the same machine code, a bunch of register loads, an arithmetic operation, return of  a register.  There is no benefit in future calls of having "result" being a variable.  If it's persistent (like a static in C/C++), you wind up wasting because you are always overwriting.

I think all of these programming paradigms boil down to "it's not a bad idea, but it may not be the best idea"


----------



## jbo (Apr 8, 2022)

WARNING: Highly personal, friday-evening based opinion incoming. Furthermore, OP clearly stated that what he tries to convey can be applied to "the language of your choice". So this is no criticism towards OP.

mer That's one of the reasons why I (currently?) like modern C++ so much. While most popular language try to address (they often call it "fix") a specific problem, modern C++ just allows you to pick what you think is most suitable. You can do OOP, you can do functional, you can do concurrency, you can do memory-safe, you can do metaprogramming, you can do <blank> - and you can mix and match those at will!

Ironically enough, those popular languages often seem to fail at "fixing" the very problem they were set out to "fix" in the first place if they evolve for long enough. At the same time, you have to deal with additional disadvantages and loss in flexibility.
I guess Java is the textbook example here with it being "the solution for embedded".

I'm a strong advocat for ensuring that developers/programmers/engineers understand the very core principles of computer science and the underlying mechanisms. Something that seems to have been lost in time. These days it's mainly about getting a result as quickly as possible. Yeah, lets use rust because I can´t make memory management mistakes. Lets use Go because I don´t have to worry about thread safety - and then you're suddenly stuck in an ecosystem that is less flexible, often more cumbersome in different ways and you still didn't learn the basics which are needed for proper design, implementation & debugging of whatever it is you're attempting to do.

Obviously (and as usual from me), I don´t mean to say that C++ is the holy grail and everything else is shit. That's certainly not the case. I'm a fan of "the right tool for the job". I just like that - at least the stuff I usually do - C++ can be the right tool.
C++ obviously has downsides, shortcomings and other problems too. We'll always find examples to support whatever argument you choose to make.


----------



## mer (Apr 8, 2022)

Warning, Early Friday PTO before a weekend opinion 
jbodenmann Glad you specified modern C++.  The language has evolved a ton since the beginning, toss in the C++ STL and one can do a lot quickly.

I think lots of languages have a place:  java I think in good for quick prototyping and stuff with GUIs (especially cross platform).

Principles and fundamentals.  Goes back to my "data + algorithms = programs".  I can't locate the book on my shelf immediately but it's an old book that still holds true.


----------



## Deleted member 70435 (Apr 8, 2022)

we can say that rust has advanced in an impressive way. today you write a kernel module in rust and you have a whole development environment ready. I'm not saying that rust is better but we have to do an analysis really

the C C++ language, are excellent for embedded systems and other components today that are gaining the market, today you have almost a whole structure for both parts.

you can develop a complete operating system in rust, the kernel completely in rust. maybe you worry about something Hardware related with no problem, as it's something who has a community, the driver can be written easily, and implemented and finally compiled, and the hardware is working as a module

I have to add another thing to the question I raised, rust for systems in general is a great language and the language of the future too, because of its modularity. you have to, solve a problem. the problem is that the developers don't accept it so easily. but we can have projects open on github with several projects
many different.


----------



## kpedersen (Apr 8, 2022)

Dimitri Chuikov said:


> and the language of the future too, because of its modularity.


I don't quite agree with this. The webdev Javascript/NPM style modularity approach that crates.io is copying does tend to crumble after a while. Dragging in dependencies left, right and center as a dependency oriented approach racks up horrific technical debt that doesn't seem to stand the test of time well.

A lean but stable standard library like C has had a provable success. It may not be objectively better as such but in practice tends to win out in the end.


----------



## shkhln (Apr 8, 2022)

Dimitri Chuikov said:


> dynamic programming isn’t a particular algorithm but a *way of thinking*.


FYI, "dynamic programming" is a deliberately selected cool sounding buzzword: https://cs.stackexchange.com/questions/17871/what-is-dynamic-about-dynamic-programming.


----------



## drhowarddrfine (Apr 9, 2022)

shkhln said:


> a deliberately selected cool sounding buzzword



As, it seems, most web programming uses nowadays.


----------



## Jose (Apr 9, 2022)

jbodenmann said:


> That's one of the reasons why I (currently?) like modern C++ so much.


Also a Friday evening take (half a beer in too!). I just happened to watch this today:




_View: https://www.youtube.com/watch?v=7DTlWPgX6zs_


Worth mentioning Mr. Josuttis is a member of the C++ Standard Committee. The more I learn about modern C++ the more I think it's time to look at something else.


----------



## kpedersen (Apr 9, 2022)

Jose said:


> Also a Friday evening take (half a beer in too!). I just happened to watch this today:


Heh, there used to be quite a funny diagram with all the different rules involves in value / zero / default initialization in C++. Annoyingly I can't quite track it down. It was very large and very complex 

I tend to use something similar to boost's value init (but not boost itself because it is a cesspit!) to just initialize my variables automatically and be done with it. Some developers moan that it is "slow" and yet don't seem to understand the other languages that they love (such as Rust) do this by default anyway...



Jose said:


> The more I learn about modern C++ the more I think it's time to look at something else.


I like C++ but I am looking into moving away from the standard library because it is still not safe enough and is starting to change a little too much to cater for all these new operators they are inventing. I will be seen as a bit of a heretic and pariah but honestly the last thing that came out that was good was around c++0x with Technical Report 1's shared/weak_ptr.


----------



## drhowarddrfine (Apr 9, 2022)

kpedersen said:


> starting to change a little too much to cater for all these new operators they are inventing.



Or change for the new people coming in who want change for the sake of change and programming is "tooooo haaaaaard". Rather than do the work, they want an app for that.


----------



## kpedersen (Apr 9, 2022)

drhowarddrfine said:


> Or change for the new people coming in who want change for the sake of change and programming is "tooooo haaaaaard". Rather than do the work, they want an app for that.


Definitely, some of the newer features are a crutch for weak (mostly careless) developers. At the same time it is really annoying to see interns (its always the interns for some reason) make a real mess for themselves with the newer async stuff. They seem attracted by it (perhaps due to Javascript tutorials).

You also see *auto *used too often in areas where the type can't be easily seen so you have to churn through all the code to find it. Nothing more annoying than seeing:


```
auto info = partition->getItemNotificationInfo();
```

What is the variable type? An *Info*, an *ItemInfo*, an *ItemNotification*, a *Notification*? You end up having to jump to the function to check whilst at the same time watching others wait for their IDE to catch up and then finally use the intellisense to decipher it. Very slow workflow.


----------



## mer (Apr 9, 2022)

One thing about all these "new and improved with a free set of Ginsu knives" features being added are you don't need to use them.
I agree on the shared/weak_ptr stuff and some of the stuff in the STL is useful so you don't need to reinvent the wheel (container stuff like the lists and maps).
One just needs to be mindful of any threading issues and dtors on object.

"You also see *auto *used too often in areas where the type can't be easily seen so you have to churn through all the code to find it."

Yep.  A huge difference between writing code and debugging/maintaining it.  Too many people "program" but someone else has to integrate and find the root cause for a bug.


----------



## kpedersen (Apr 9, 2022)

mer said:


> One just needs to be mindful of any threading issues and dtors on object.


Multi-threading is one specific reason for me to avoid the standard library, it just isn't geared up for it. They are trying with lockless atomics and things like that but it is the design that isn't really suitable. The smart-pointers and (atomic) reference counting need to be considerably different in my opinion.



mer said:


> Too many people "program" but someone else has to integrate and find the root cause for a bug


"Write-only" code


----------



## Jose (Apr 9, 2022)

drhowarddrfine said:


> Or change for the new people coming in who want change for the sake of change and programming is "tooooo haaaaaard". Rather than do the work, they want an app for that.


And the irony being they're actually making it much harder. Mr. Josuttis teaches C++ to beginners, and part of that talk is him complaining that he doesn't know what to teach. One of the funnier slides is where he points out there are at least 19 ways to initialize an int.



kpedersen said:


> You also see *auto *used too often in areas where the type can't be easily seen so you have to churn through all the code to find it. Nothing more annoying than seeing...


You are such a heretic Mr. Pedersen! Haven't you heard that you should AAA (Almost Always use Auto)? Josuttis has a great slide where he makes fun of this.


----------



## shkhln (Apr 10, 2022)

kpedersen said:


> ```
> auto info = partition->getItemNotificationInfo();
> ```
> 
> What is the variable type? An *Info*, an *ItemInfo*, an *ItemNotification*, a *Notification*? You end up having to jump to the function to check whilst at the same time watching others wait for their IDE to catch up and then finally use the intellisense to decipher it. Very slow workflow.


On the other hand, once you declare a type you immediately know all of the methods you can call without ever consulting the documentation (or looking at the class declaration), right?


----------



## eternal_noob (Apr 10, 2022)

At first i refused to use *auto* since i am a bit conservative and sceptic about things added to "modern" C++.
But now i use it everywhere i can. Simplifies things a lot.


----------



## mer (Apr 10, 2022)

Use of auto can indeed simplify the way the code looks because you can have shorter lines because it's only 4 characters.  And when you are simply writing code it's faster to type.  (yes, that is sarcasm there).

If you declare a type, no of course you don't immediately know everything about it, but at least you have a starting point for grepping.  That makes finding and fixing (root causing) bugs just a little bit easier.
The line of code quoted you need to start by  looking at what "partition" is, if there is only a single method named getItemNotificationInfo() then you know what type "info" is.  But if getItemNotificationInfo() is overloaded, then you spend more time looking at how "info" is used before you know what type it is.

Toss in C++ classes and you may wind up spending more time looking at code to figure out what "info" is.

Whole lot of difference  between simply writing code and having to pick up someone else's code months later to fix a bug.

Maybe auto is good because it can help focus on the "what something does" instead of "how something is done" (thinking Object Oriented design).
Maybe it's good because you can write a good algorithm once using auto and then cut and paste it everywhere in your code without having to edit it as much, but of course one could use a template for that too.

One of the best things about all these new things added to C++:
You don't have to use them.


----------



## kpedersen (Apr 10, 2022)

shkhln said:


> On the other hand, once you declare a type you immediately know all of the methods you can call without ever consulting the documentation (or looking at the class declaration), right?


Of course.


```
ClassContainingIdNameEmployeeNumberDepartmentPointerAndManagerId myemp = findEmp();
```

I also dislike it when *lazy* programmers aren't descriptive with their naming. 

At the very least though, once you know the type's name, you generally know which header to scan through.


----------



## eternal_noob (Apr 10, 2022)

kpedersen said:


> ClassContainingIdNameEmployeeNumberDepartmentPointerAndManagerId myemp = findEmp();


Should be

```
auto ClassContainingIdNameEmployeeNumberDepartmentPointerAndManagerId = findEmp();
```
Descriptive variable names are important.


----------



## mer (Apr 10, 2022)

If you're going to use auto it would be
auto myEmp = findEmp();

I don't think this would even compile, you are trying to use a class name as a variable name.

       auto ClassContainingIdNameEmployeeNumberDepartmentPointerAndManagerId = findEmp();


----------



## eternal_noob (Apr 10, 2022)

mer said:


> auto myEmp = findEmp();


Prefixing variable names with "my" is laughable imho.


mer said:


> I don't think this would even compile, you are trying to use a class name as a variable name.


Yes, you're right. Should be a lower case "C". I just copy n pasted without changing it since i am lazy.


----------



## mer (Apr 10, 2022)

eternal_noob said:


> Prefixing variable names with "my" is laughable imho.


Now we're all just peeing in a pot and claiming it's raining. My example was simply following what kpedersen used except for my use of camel case (simply because current $WORKPLACE coding standards....)



eternal_noob said:


> Yes, you're right. Should be a lower case "C". I just copy n pasted without changing it since i am lazy.



And a realife example of the perils of cut and paste


----------



## kpedersen (Apr 10, 2022)

Well I agree and think descriptive class *and* variable names are important. So...


```
ClassContainingIdNameEmployeeNumberDepartmentPointerAndManagerId classContainingIdNameEmployeeNumberDepartmentPointerAndManagerId = findEmp();
```

This codebase would be a joy to read!

(I only really use "my" in names for trivial code examples where you don't have (or need) the context to know if it is a parameter, a member or neither. It is mostly pointless though admittedly)


----------



## mer (Apr 10, 2022)

Although if as part of a corporate merger one was responsible doing something with 2 different employee databases, variable names such as "myEmp and theirEmp" would make some sense.


Ok, it would be "nonsense" but....


----------



## Deleted member 70435 (Apr 10, 2022)

thanks for the comment my friends i am grateful to you. I will make a special recommendation for you

I hope you guys have a good read and maybe even thank me for it, today it's hard for anyone to extend knowledge to someone else, as I'm an old-timer I appreciate knowledge of course it makes us effective.






						I. Dynamic Programming - algo-en
					






					labuladong.gitbook.io


----------



## Deleted member 70435 (Apr 10, 2022)

if there was a way to approach it I just think it would be boring. the linux kernel is boring in itself no offense but i'm tired of having to complain about the same things..

when will someone think differently developing the linux kernel, and giving the voice to the linux user. maybe they want to keep it hidden from their users


----------



## Deleted member 70435 (Apr 10, 2022)

all i hate is something in particular that something that goes against philosophy. maybe some developer will make a suggestion of how to develop and how to optimize the code be crucified for this. our freedom to think about how things are made does not exist. I thought very well when I entered this area I knew it was so.
the world does not work as we think, that we can defend our interests, our philosophy and our cultures.


----------



## Jose (Apr 10, 2022)

kpedersen said:


> ```
> ClassContainingIdNameEmployeeNumberDepartmentPointerAndManagerId myemp = findEmp();
> ```
> 
> I also dislike it when *lazy* programmers aren't descriptive with their naming.


Well there are only 2 hard problems in computer engineering. Naming things, cache invalidation, and off-by-one errors.


----------



## mer (Apr 10, 2022)

Jose said:


> Naming things, cache invalidation, and off-by-one errors.


Funny man.


----------



## _al (May 28, 2022)

Jose said:


> Worth mentioning Mr. Josuttis is a member of the C++ Standard Committee.


As an advertisement - https://leanpub.com/cpp20


----------



## zirias@ (May 28, 2022)

Grumpy old software architect here, I never heard of "dynamic programming", and I don't think I really missed anything so far...

I _did_ see lots of "awesome" ideas go down the drain over time, though. To name just some: SOA and SOAP, and maybe also, to some extent, OOP, at least as people started to realize deep inheritance trees (especially if behavior is inherited as well) are the new spaghetti code, well on par with the worst stuff you could create with "goto" as your only control structure . Ok, that didn't kill OOP, but it changed what's considered a good OOP design.

I wish people in the business would stop inventing buzzwords. Sure, you have to name your idea somehow. Most of the few software design principles that proofed to be of lasting value have descriptive names, though, like e.g. the single responsibility principle.

(No, I don't judge this concept to be bad here. I just learned some scepticism )


----------



## jbo (May 28, 2022)

Zirias said:


> Grumpy old software architect here, [...], well on par with the worst stuff you could create with "goto" as your only control structure .


While I might not be as old as you I've been told that I'm certainly decades ahead on the grumpy-ness. But is it really my fault that most things seem to truly suck these days?
Anyway, I came here as I'd like to argue that there are still cases where using `goto` is the superior solution (yes, also in terms of readability).

Academically, new programmers are told very early on that "goto is bad" but often no explanation for this is given, especially in the basic courses/lectures. This managed to get to a point where novice programmers seem to be simply scared of goto. They look at your code, they see a goto somewhere and they react like there's a pile of dead human bodies in your drawer.
I know a lot of "less experienced programmers" that truly think that there is something wrong with goto on a technical level, that it creates incorrect instructions or whatever. But that is simply not true. The main (and as per my current knowledge only) reason for goto to be considered a bad thing is that it very easily allows to create nontransparent code that is hard to read and maintain. But as with most things: If used incorrectly, it sucks - yeah. But that doesn't mean that the use of goto itself is bad or forbidden.

One place where I still find myself using goto is in initialization sequences that have non-trivial clean-up sequences attached to them (eg. multiple stages/phases of initialization where you have to perform the cleanup in a particular sequence if you have to abort mid-way).
I think the poster child here are drivers. There, properly used goto makes for much easier to read - and I'd argue safer - code compared to not using goto.


----------



## zirias@ (May 28, 2022)

jbodenmann said:


> Anyway, I came here as I'd like to argue that there are still cases where using `goto` is the superior solution


Don't really know why argue? There's a reason I wrote "as your only control structure"


----------



## jbo (May 28, 2022)

Zirias said:


> Don't really know why argue? There's a reason I wrote "as your only control structure"


Yeah, I might have chosen my words poorly there. I did not mean to argue _against_ you


----------



## zirias@ (May 28, 2022)

jbodenmann, if we're really discussing that, my take on it is: `goto` is a _huge_ gain in _some_ (often idiomatic) cases when the language is somewhat close to machine code (e.g. requires explicit resource management). In other words, it has a few very good uses in C and, to a lesser extent, C++.

Looking at other languages, for example C#, in all my time writing C# code, I didn't find a single good use for `goto`. For your typical scenarios, you're much better off using `try-finally` and/or `using` blocks. In C++, you _could_ do a similar thing if you want to wrap everything with exceptions and strictly follow RAII. But that's another story (IMHO the combination of exceptions with explicit resource management is a broken concept), I don't think that's _always_ a good idea. In C, trying to dogmatically avoid `goto` where you'd normally need it just leads to weird things like abusing other control structures in creative ways, so yes, unreadable code.


----------



## Deleted member 70435 (May 28, 2022)

this week i had a nasty argument with a russian friend of mine because he thinks perl is an outdated language i thought it was a punch in the gut. I put my opinion on Perl and I also consider goto something that involves us a lot with algorithms of how to actually enter a project. it's not like walking down a dark alley.

today this generation of programmers they never knew how to distinguish a superior software designer and how this is possible. math algorithms 24 hours of study don't take your college professor's ideas as dogmatic if you stick to one thing. I like Pythagoras because he says something far beyond math and algorithmic calculations


----------



## mer (May 28, 2022)

I'll see your goto and raise you a setjmp/longjmp 

As "YAGOP/SA" any tool becomes bad when used incorrectly.  Screwdrivers to open paint cans?  No, they make can openers for that.  
My opinions:
OOP is good if it makes you stop and think:  you design something correctly and implement it in whatever language and prove correctness.
Why do all the "new and improved with a free set of knives" languages compare themselves to C/C++?
I have a book somewhere, title is something like "Data + Algorithms = Programs".  To the best of my knowledge, that is still true.
So think about the problem, design the solution, implement it correctly in whatever language and who cares what anyone else says.


----------



## jbo (May 28, 2022)

Dimitri Chuikov said:


> [...] he thinks perl is an outdated language [...]


What is an outdated language anyway? Either it's the right tool for the job or it isn't. The only thing that changes is that more choices become available as time moves forward.
If the language (and surrounding ecosystem) are alive & well maintained it's just a language available that may or may not be the right tool for the job.

C is outdated and I still write C code every damn day for fun and profit. Why? Because it actually isn't an outdated language but rather happens to be the language of choice for some situations.

This is in my opinion similar to "BSD is dying". Just because there are more options available compared to 25 years ago doesn't mean that BSD is dead. It might just be that for a particular situation another OS might be the preferred choice (which does not necessarily need to be a technically driven decision).
Let alone the fact that these days orders of magnitudes more people actually use computers. Those people might have different requirements & preferences which might make BSD the non-chosen option but that doesn't mean that BSD is dying. I'd even guess that the absolute number of FreeBSD has increased over the years. Just realtively there might be a decline because more people use more different non-(Free)BSD operating systems. FreeBSD is still doing well despite that.

Newly available options (eg. new languages or new operating systems) don't automatically make the previously existing stuff outdated or obsolete.


----------



## Deleted member 70435 (May 28, 2022)

jbodenmann said:


> What is an outdated language anyway? Either it's the right tool for the job or it isn't. The only thing that changes is that more choices become available as time moves forward.
> If the language (and surrounding ecosystem) are alive & well maintained it's just a language available that may or may not be the right tool for the job.
> 
> C is outdated and I still write C code every damn day for fun and profit. Why? Because it actually isn't an outdated language but rather happens to be the language of choice for some situations.
> ...


I personally don't think BSD is dying. what is really dying is people's ability to understand the needs of each industrial sector, today students want something ready, so that they can just enjoy the algorithm that we spend day and night implementing


----------



## grahamperrin@ (May 28, 2022)

Dimitri Chuikov said:


> I personally don't think BSD is dying.



Quoting _The Register_:



> … easier to get 13.1 up and running than any previous version of FreeBSD we've tried. As such, we're impressed. … The future looks promising for this OS with its roots in the early 1970s. ®


----------



## hruodr (May 28, 2022)

jbodenmann said:


> Anyway, I came here as I'd like to argue that there are still cases where using `goto` is the superior solution (yes, also in terms of readability).


It is very easy to see that "goto" is more expressive and hence better readable if one do not abuse of it.

It is very simple to implement a "while" or a "for" with "goto", and you get something readable, but of course,
more readable are "whiles" and "fors". We cannot say the opposite. To implement an arbitrary "goto" with
other control structures, you can have a big switch inside a while encompassing the whole program, that is not
very readable. Normally one uses flag variables to avoid a "goto", that is also an artificial solution.

As someone that learned programming with old pocket calculators, with FORTRAN IV, this is clear to me.
I really do not know what people thinks that learned "structured programming" from the beginning, that were
told that gotos is bad stile.


----------



## bakul (May 28, 2022)

Dimitri Chuikov said:


> As shown, there’s a significant increase in the number of times our function is called. Similar to our previous example, the algorithm’s performance decreases exponentially based on the input size. This occurs because the operation does not store previously calculated values.


Try this:

```
(define (fib n)
  (if (< n 2)
     n
     (let* ((k (quotient (+ n 1) 2)) (fk-1 (fib (- k 1))) (fk (fib k)))
         (if (even? n) (* fk (+ fk (* 2 fk-1))) (+ (* fk fk) (* fk-1 fk-1))))))
```
This recursive version is likely faster than your memoized version for large n! Try something like 

```
(time (begin (fib 10000000) #t))
```
in `gsi-gambit` from gambit-c.


----------



## Deleted member 70435 (May 28, 2022)

bakul said:


> Try this:
> 
> ```
> (define (fib n)
> ...


----------



## Deleted member 70435 (May 28, 2022)

bakul said:


> Try this:
> 
> ```
> (define (fib n)
> ...


now change the position if performance is the case then develop a more effective algorithm for this problem that is the goal of this thread


----------



## hardworkingnewbie (May 29, 2022)

jbodenmann said:


> Academically, new programmers are told very early on that "goto is bad" but often no explanation for this is given, especially in the basic courses/lectures. This managed to get to a point where novice programmers seem to be simply scared of goto. They look at your code, they see a goto somewhere and they react like there's a pile of dead human bodies in your drawer.


Well, this is the achievement/fault of this man here:





Please meet Edsger Wybe Dijkstra (*11/04/1930, +05/08/2002), a computer scientist from the Netherlands and one of the most influential ones of the founding days. He's quite well known for his achievements in computer sciences, and gained the Turing Award already back in 1972.

Amongst his works are the Dijsktra Algorithm, which determines the shortest path between nodes in a graph, creation of the ALGOL-60 compiler, and more.

To quote the Wikipedia: _One of the most influential figures of computing science's founding generation,[2][3][5][6][12][13] Dijkstra helped shape the new discipline both as an engineer and a theorist.[14][15] His fundamental contributions cover diverse areas of computing science, including compiler construction, operating systems, distributed systems, sequential and concurrent programming, programming paradigm and methodology, programming language research, program design, program development, program verification, software engineering principles, graph algorithms, and philosophical foundations of computer programming and computer science. Many of his papers are the source of new research areas. Several concepts and problems that are now standard in computer science were first identified by Dijkstra or bear names coined by him.[16]__[17]_

As you might have noticed, he also worked on programming paradigms and was a fan of structured programming. Wearing this hat he wrote a very influential article named "Go to statement considered harmful" back in 1968 (Link to scan of that original | Link to HTML version). Actually this is one of the most influential opinion pieces in computer science ever.

So whoever is lecturing at least should have the courtesy of pointing to that classic article, which initiated later a myriad of "$STUFF considered harmful" opinions. It's also a short read, only two sheet of paper.


----------



## hardworkingnewbie (May 29, 2022)

jbodenmann said:


> What is an outdated language anyway? Either it's the right tool for the job or it isn't. The only thing that changes is that more choices become available as time moves forward.


How about MUMPS (short for _*M*assachusetts General Hospital *U*tility *M*ulti-*P*rogramming *S*ystem)_? Yes, that's a *ancient *real life programming language, and oh boy it sucks. But since it is still widely used in the American Health Care System there's still a steady need of developers for it.

It was maybe the right tool for its job back in the old days 1966 because there wasn't much else, but nowadays... OUCH. Im pretty sure nobody sane would consider starting new projects in MUMPS these days, but there's so much legacy code around which still powers so much so...

Some shortened source code goodnees (taken from Wikipedia).


```
%DTC ; SF/XAK - DATE/TIME OPERATIONS ;1/16/92  11:36 AM
     ;;19.0;VA FileMan;;Jul 14, 1992
D    I 'X1!'X2 S X="" Q
     S X=X1 D H S X1=%H,X=X2,X2=%Y+1 D H S X=X1-%H,%Y=%Y+1&X2
     K %H,X1,X2 Q
     ;
C    S X=X1 Q:'X  D H S %H=%H+X2 D YMD S:$P(X1,".",2) X=X_"."_$P(X1,".",2) K X1,X2 Q
S    S %=%#60/100+(%#3600\60)/100+(%\3600)/100 Q
     ;
H    I X<1410000 S %H=0,%Y=-1 Q
     S %Y=$E(X,1,3),%M=$E(X,4,5),%D=$E(X,6,7)
     S %T=$E(X_0,9,10)*60+$E(X_"000",11,12)*60+$E(X_"00000",13,14)
TOH  S %H=%M>2&'(%Y#4)+$P("^31^59^90^120^151^181^212^243^273^304^334","^",%M)+%D
     S %='%M!'%D,%Y=%Y-141,%H=%H+(%Y*365)+(%Y\4)-(%Y>59)+%,%Y=$S(%:-1,1:%H+4#7)
     K %M,%D,% Q
     ;
DOW  D H S Y=%Y K %H,%Y Q
DW   D H S Y=%Y,X=$P("SUN^MON^TUES^WEDNES^THURS^FRI^SATUR","^",Y+1)_"DAY"
     S:Y<0 X="" Q
7    S %=%H>21608+%H-.1,%Y=%\365.25+141,%=%#365.25\1
     S %D=%+306#(%Y#4=0+365)#153#61#31+1,%M=%-%D\29+1
     S X=%Y_"00"+%M_"00"+%D Q
     ;
```

And some of the features of that language:



> CASE SENSITIVITY: Commands and intrinsic functions are case-insensitive. Variable names and labels are case-sensitive.
> COMMANDS: may be abbreviated to one letter, case-insensitive. Includes commands such as IF, ELSE, GOTO, WRITE, and XECUTE [which is my personal favorite, it allows arbitrary execution of code contained in a variable]
> OPERATORS: No precedence, executed left to right, parenthesize as desired. 2+3*10 yields 50.
> DATA TYPES: one universal datatype, interpreted/converted to string, integer, or floating-point number as context requires.
> ...











						A Case of the MUMPS
					

You may not realize it, but the majority of us developers have been living a sheltered professional life. Sure, we’ve got that living disaster of a C++ application and that ridiculous interface between PHP and COBOL written by the boss, but I can assure you, that all pales in comparison to what...



					thedailywtf.com


----------



## bakul (May 29, 2022)

jbodenmann said:


> They look at your code, they see a goto somewhere and they react like there's a pile of dead human bodies in your drawer.


Enquiring minds want to know: how big is your drawer?!

The Go language has the "defer" statement precisely for the situation where you use goto. Still, the real point is not "goto considered harmful" but "spaghetti code considered harmful" and you can write spaghetti code without even a single goto! This is why things like "Cyclomatic Complexity" and "Halstead Volume" and "Maintainability Index" came about.


----------



## hruodr (May 29, 2022)

hardworkingnewbie said:


> So whoever is lecturing at least should have the courtesy of pointing to that classic article,


I you mean with "lecturing" to express an opinion, then, with all respect to authorities like Dijkstra, I differ, I do not recognise the necessity to continuously point to authorities.


----------



## hardworkingnewbie (May 29, 2022)

Well, as jbodenmann rightfully stated, many freshman students on universities are being told goto is bad by their lecturers. Not much more information given than that.

So at least their lecturers should tell them in my opinion where this comes from - Dijkstra's classic article - and that this is not written in stone. Some might have different views about it, and with good reason! Because nothing is more worse than learning something early as big nono without knowing why.


----------



## Deleted member 70435 (May 29, 2022)

what we have to observe is that we don't have to hide behind the philosophy of professors, this limits us a lot in programming. our unix philosophy the program should be simple it's well done that's what i stand for. but some issues you raised he considered an excellent scientist by his work. dynamic programming algorithms that complement each other, sometimes mathematics surprises us by an unknown but not obscure universe. every engineer knows what it's like to spend years and hours trying to make his work not the best known. but each time better for humanity and each time possible to be something accessible, for all

I always argue don't do a program, do something special for people. let her see how our FreeBSD is something made for people with all their qualities


----------



## obsigna (May 29, 2022)

jbodenmann said:


> One place where I still find myself using goto is in initialization sequences that have non-trivial clean-up sequences attached to them (eg. multiple stages/phases of initialization where you have to perform the cleanup in a particular sequence if you have to abort mid-way).


I completely agree. I only would like to make the use case more general:

_Goto’s are useful/needed for jumping out of the regular program flow._​
Your example fully fits the bill.

Even Pascal, which was once THE language of choice for teaching programming have goto’s like C. Why? It keeps code for the regular logic clean, while at the same time you’re able to treat irregular cases, like insufficient resources, unexpected input, out-of-limit results, etc. in a sane way.


----------



## Deleted member 70435 (May 29, 2022)

I just dedicate myself some language like C Language, Rust Perl Language

I don't see so much need, to learn, so much language, but nowadays they teach about language and give little importance to the algorithm and you have young people insecure when it comes to producing something.

you know i have my limits i want a woman to go out with me sometimes, and talk about how your day was. and so we'll start a conversation about work. what I see in these young amateurs and think they think they know everything they know everything. just because you learned or read a book in several languages.

to learn a language really requires 5 years of dedication, and being a person who likes to contribute to some project


----------

