3

Please demonstrate first-class functions (or some other functional programming concept) for code reuse for a beginner using these two overlapping Clojure functions. Basically, simplify the code block below using functional programming methods.

As a comparison, how would you do it in your other functional language of choice?

insertR and insertL are simple first-occurrence insertion functions. As you can see, they only differ by one line.

;test case
(def newkey :cake)
(def oldkey :and)
(def lat '(:bacon :lettuce :and :tomato :and :jelly)) ; list of keywords

(defn insertR [newkey oldkey lat]
  (if (empty? lat)  
    '()
    (if (= (first lat) oldkey)
        (cons oldkey (cons newkey (rest lat))) ;;; diff line
        (cons (first lat) (insertR newkey oldkey (rest lat))))))

(defn insertL [newkey oldkey lat]
  (if (empty? lat)
    '()
    (if (= (first lat) oldkey)
        (cons newkey lat)  ;;; diff line
        (cons (first lat) (insertL newkey oldkey (rest lat))))))

Here are the outputs.

=> (insertR newkey oldkey lat)
(:bacon :lettuce :and :cake :tomato :and :jelly)
=> (insertL newkey oldkey lat)
(:bacon :lettuce :cake :and :tomato :and :jelly)
Rachel Shallit
  • 2,002
  • 14
  • 15
Paul Lam
  • 1,729
  • 1
  • 15
  • 25
  • No. I'm learning functional programming on my own and this question just came up to me. I can do it in OO through a Template pattern but couldn't figure out how to do it in FP. – Paul Lam May 17 '11 at 15:24

1 Answers1

2

Here's an example of refactoring this using first-class functions:

(defn insert [newkey oldkey lat f]
  (if (empty? lat)
    '()
    (if (= (first lat) oldkey)
      (f oldkey newkey lat)
      (cons (first lat) (insert newkey oldkey (rest lat) f)))))

(defn insertL [newkey oldkey lat]
  (insert newkey oldkey lat 
    (fn [oldkey newkey lat] (cons newkey lat))))

(defn insertR [newkey oldkey lat]
  (insert newkey oldkey lat 
    (fn [oldkey newkey lat] (cons oldkey (cons newkey (rest lat))))))
Rachel Shallit
  • 2,002
  • 14
  • 15
  • Yes, this works for this particular example. I'm looking for some illustrations of functional programming to show a more robust method. In particular, how can I make use of first-class functions in this? – Paul Lam May 17 '11 at 15:28
  • 1
    mmhh thats not really clojury. Replace (if (empty? lat) '() ....) with (when (seq lat) ...). In clojure we replace nil instead of the empty list. – nickik May 17 '11 at 18:42
  • @nickik - this question is about showing a beginner how to use first-class functions, not about adherence to Clojure idioms... – Rachel Shallit May 17 '11 at 21:55
  • 1
    @rshallit Sure, but I think spezially for beginners its importend to learn the right (clojure) way. It was be no means a critizism just a little add on. – nickik May 18 '11 at 06:43