Question
use haskell language Assume we want to implement a word sum that expects (a pointer to) an array of numbers on the top of the
use haskell language
Assume we want to implement a word sum that expects (a pointer to) an array of numbers on the top of the stack and replaces it with the sum of all array elements. Here is how we would implement it. The word itself is annotated with the typical stack effect annotation. It shows that the array arr is popped from the stack and the sum of its elements sum(arr) is pushed onto the stack. I have annotated each of the other lines with the state of the stack once execution reaches the end of this line, in order to allow you to trace the execution. Whenever I use >r an r> to move data between the data stack and the recursion stack, I use the notation /
: sum ( arr -- sum(arr) ) dup len 0 0 >r ( arr n 0 / sum ) ( n refers to the length of the array. ) ( sum refers to the sum of the array elements, ) ( which is initially 0. ) dup2 > ( arr n 0 n>0? / sum ) while ( arr n i / sum ) ( i refers to index of the next element to be ) ( added to sum. ) rotl swap dup2 read ( n arr i arr[i] / sum )r ( n arr i / sum+arr[i] ) 1 + ( n arr i+1 / sum+arr[i] ) rotl swap ( arr n i+1 / sum+arr[i] ) dup2 > ( arr n i+1 n>i+1? / sum+arr[i] ) repeat ( arr n n / sum(arr) ) drop drop drop This code uses the word dup2 we defined earlier to duplicate the top two elements on the stack.
your task for this question. Implement a word insertion_sort ( arr -- ). In other words, this word expects a pointer to an array of numbers on the stack. It pops this pointer from the stack and pushes nothing new onto the stack. The side effect this word should have is to arrange the elements in arr in sorted order, using Insertion Sort. You are welcome to define helper words such as dup2 that you can use in your implementation of Insertion Sort. Indeed, defining such helper words is common practice among FORTH programmers because the stack effects of more complex words such as insertion_sort are hard to understand if we implement these words using only the built-in words.
Correct implementation of Insertion Sort
Correct manipulation of stack
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started