As I continue my quest of learning functional programming, I’ve come to wonder if there may be alternatives to my default ‘procedural’ way of thinking. To be more specific, I’m looking at a function I wrote. Here is what it does:
Swap two elements of an unordered list of numbers, such that one of the elements is now in the right place Add the sum of the swapped values to an accumulated total Repeat until list is sorted
So, right now I’m using a standard loop* with an accum variable to do the above. It works fine and all, and there’s certainly nothing wrong with iteration in real life, but as the point of this exercise is to expand my way of thinking, I’m curious if there is a more functional approach to the above algorithm.
Thanks!
*(Actually recursion, but whatever)
Edit: Referring to Xavier Leroy, primary developer of OCaml
Since I can’t see your function to understand how functional* it is, I don’t know. But it seems like what you are doing is correct. My main suggestion would be looking at data structures that lend themselves well to functional programming –but you are using lists, so that’s out, although, lists aren’t the best data structure in this case. As well as the algorithm. If you are pigeon holed into using the insertion sort, then you might not be able to use merge sort or other more efficient methods.