I have this definition “sort left list” which is a list of pairs sorted according to the left element of each pair the left element must be a non-negative integer and the right component may be a value of any type
I have to write a procedure mkjump which takes as an argument a sorted list of non-negative integers,
sorted-lst = (x1 … xn) and returns a left-sorted list:
sort left list = ((x1.y1)…(xn.yn)) such that: yi is the largest suffix of sort left list,
((xj . yj)…(xn . yn)) in which xk>(xi)^2 for all xk. For example:
>(define lst (list 2 3 4 15 16 17))
>(mkjump lst)
>lst
( (2 (15) (16) (17))
(3 (15) (16) (17))
(4 (17))
(15)
(16)
(17) )
The 6th element in res is (x6 . y6) where x6=17 and y6=null. The 3rd element in res is (x3 . y3),
where x3=4 and y3 is the list containing (x6 . y6), which is the largest suffix of res in which xk>(xi)^2
for all xk
How to write it?
As stated previously you do not need mutable state to do your job. However, if you really want to use them you can easily change Keen’s solution to get what you want. First you have to translate his code in a tail recursive way. You can begin with
mkjumpThen you can change
modmapThe tail recursive
mkjump-trwill be translated in an iterative process. This is because it can be seen as a while loop. This enable you to create this loop with thedoconstruction. This waymkjump-trcan be write asand
modmap-trcan be translated asBut since we do not have recursive form, we can directly write these
do‘s in the former functionsmkjumpandmodmap. So we getYou could see some slight changes:
reverseis added beforesolandsolis initialize by the empty list in both case.Finally, if you really want to see some
set!somewhere, just add them by breaking thedo-loop construction. Here is the solution formkjumpI will let you change
modmap. These two last modifications obfuscate the idea behind the algorithm. Therefore, it is a bad idea to change them this way, since they will not improve anything. The first modification can be a good idea however. So I will suggest you to keep the first modification.Is this what have you expected ?