I'm learning Haskell and I decided to implement this simple algorithm for doing part of the insert sort algorithm:
while j > 0 and A[j-1] > A[j]
swap A[j] and A[j-1]
j ← j - 1
end while
I did like this:
miniSort:: (Eq(a), Ord(a)) => Int -> [a] -> [a]
miniSort j list = if (list !! j) < (list !! (j-1)) && j >0
then miniSort (j-1) (swapElements j (j-1) list)
else list
It was kinda hard to get it right but I did (I guess).
While in imperative programming languages to view each step I could simply do
while j > 0 and A[j-1] > A[j]
print("j is $j")
print("swapping $A[j] with $A[j-1]")
swap A[j] and A[j-1]
print("swapped list: $A")
j ← j - 1
end while
print("ended with j $j")
On Haskell it's much much harder to insert logging functionality through the Writer Monad. I didn't even try because it would be a mess, and then when I wanted to clean the logging things it would be another mess.
Isn't there a way to view the function calls branching in Haskell?
For example:
miniSort 3 [1,2,4,3,7,8,5]
Would expand to something like this:
miniSort 3 [1,2,4,3,7,8,5] = if (3) < 4 && 3 >0
then miniSort (2) [1,2,3,4,7,8,5]
miniSort 2 [1,2,3,4,7,8,5] = if (3) < 2 && 2 >0
else [1,2,3,4,7,8,5]
[1,2,3,4,7,8,5]