Search code examples
functional-programmingracketcode-duplication

how not to duplicate code in Racket


well I came across a function that I wrote that uses the same code a few times.

here is an example:

(define (get-min&max-from-mixed-list mixedList)

  (if (null? (sublist-numbers mixedList))
      '() 
      (min&maxRec (sublist-numbers mixedList) 
                  (first (sublist-numbers mixedList)) ; this
                  (first (sublist-numbers mixedList))) ; and this
      )
  )

In a procedural programing language I wouldve done:

   int x =  (first (sublist-numbers mixedList))
   min&maxRec(sublist-numbers(mixedList) , x , x)

From my understanding of Functional languages we don't save stuff in the memory and afterwards, we use them. So how can I not duplicate code?


Solution

  • You can use let to bind a value to a symbol & use that symbol as often as you like within the let body.

    The documentation for it & related forms are here: https://docs.racket-lang.org/reference/let.html

    You could use it in your example like this:

    (define (get-min&max-from-mixed-list mixedList)
        (let ((snm (sublist-numbers mixedList)))
            (if (null? snm)
                '() 
                 (min&maxRec snm 
                             (first snm)
                             (first snm))
            )
        )
    )