<aside> 💡 Helper functions need to be created within a function if:
The function composition rule states that
Function compositions (i.e. functions with helper functions) must be used when a function performs 2 or more distinct and complete operations on input data.
A function which needs to print images from a list out in increasing order of size needs to be written.
Such a function operates on the input data in 2 steps:
Each step requires 1 helper function each.
With what we’ve learnt so far, arbitrary-sized data will give rise to the following function template:
ListOfImage
arrange-images
function.#;
(define (arrange-images loi)
(cond [(empty? loi) EMPTY_SQ]
[else
(beside (first loi)
(arrange-images (rest loi)))]))
However, the function composition rule will revise the function template into the following code instead:
(define (arrange-images loi)
(layout-images (sort-images loi)))
The Operating on a List Rule comes into play when you are designing functions which modify elements in a list.
According to Kiczales, this rule states that:
If you're coding a function and you reach a point where you need to operate on a list — not just the first element of the list, but the whole list, or at least potentially the whole list — then you need a helper function to do that.
In the example below, the function sort-images
was created to sort a list of images by size (in increasing order).
sort-images
will require a helper function in accordance to this rule.insert
is used to determine how images in a list can be sorted into their rightful positions in the list.;; ListOfImage -> ListOfImage
;; sort images in increasing order of size (area)
(check-expect (sort-images empty) empty)
(check-expect (sort-images (cons I1 (cons I2 empty)))
(cons I1 (cons I2 empty)))
(check-expect (sort-images (cons I2 (cons I1 empty)))
(cons I1 (cons I2 empty)))
(check-expect (sort-images (cons I3 (cons I1 (cons I2 empty))))
(cons I1 (cons I2 (cons I3 empty))))
;(define (sort-images loi) loi)
(define (sort-images loi)
(cond [(empty? loi) empty]
[else
(insert (first loi)
(sort-images (rest loi)))])) ;result of natural recursion will be sorted