Demonstrate first-class functions in this simple example [closed]
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.
=>开发者_StackOverflow社区 (insertR newkey oldkey lat)
(:bacon :lettuce :and :cake :tomato :and :jelly)
=> (insertL newkey oldkey lat)
(:bacon :lettuce :cake :and :tomato :and :jelly)
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))))))
精彩评论