问题
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)
回答1:
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))))))
来源:https://stackoverflow.com/questions/6033006/demonstrate-first-class-functions-in-this-simple-example