I'm doing some toy problems in a variety of languages and wanted to do the following in Racket Lisp.
Given a sorted integer array nums
, where the range of elements are in the inclusive range [lower, upper]
, return its missing ranges.
0, 1, 3, 50, 75
Lower: 0
Upper: 99
Expected Output:
["2", "4->49", "51->74", "76->99"]
As you can see on the linked page I had to take two whacks at it but eventually came up with the following. How does it look? Is it idiomatic? Could I have done certain things far better?
(define (missing-ranges nums lower upper)
(in-generator
(define (yield-missing-range current num)
(yield (if (eq? num (add1 current))
(~a current)
(~a current "->" (sub1 num)))))
(let recur ([remaining-nums nums]
[current lower])
(match remaining-nums
[(cons num rest-nums) (if (< current num)
(begin
(yield-missing-range current num)
(recur rest-nums num))
(recur rest-nums (add1 current)))]
['() (cond [(<= current upper)
(yield-missing-range current (add1 upper))])]))))